2017-02-27 87 views
0

其实我不得不提出一些问题,但主要的一点是,一旦我发出更改并在componentWillMount中捕获它以创建setState,如何将该状态更改回其以前的值?我尝试在componentDidMount上编写setState,但它会引发最大堆栈调用。将状态更改为以前的值

我也使用mdl的UI,我注意到,如果我移动组件,像materialSnackbar函数一些功能停止工作。我不知道这是否与我使用反应路由器的事实有关,并且这些使用这些功能的组件是props.children

回答

0

如果您想要回退组件的状态,您将需要将其存储在父组件中以便倒回。目前在香草反应中,没有办法重新组织的内部状态,而不在其他地方追踪它。

所以让我们说,你有以下组件

class ParentComponent extends React.Component { 
    getInitialState() { 
     return({ 
      stateHistory: [ 
          { name: "foo" }, 
          { name: "bar" } 
          { name: "baz" } 
          ], 
      stateHistoryIndex: 0 
     }) 
    }, 

    onRewind() { 
     this.setState({ 
      stateHistoryIndex: this.state.stateHistoryIndex += 1 
     }); 
    }, 

    render() { 
     return(
      <div> 
      <ChildComponent 
       data={this.state.stateHistory[this.state.stateHistoryIndex]} 
        handleRewind={this.onRewind} 
       /> 
      </div> 
     ) 
    } 
} 

class ChildComponent extends React.Component { 
    render() { 
     return(
      <div> 
       Hi, my name is {this.props.data.name} 
       <button onClick={() => this.props.handleRewind()}>Rewind</button> 
      </div> 
     ) 
    } 
} 

,你可以看到,我们需要通过它我们可以通过子控件的索引的状态存储在一个父组件和访问它。

相关问题