2017-02-27 85 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> 
     ) 
    } 
} 

,你可以看到,我們需要通過它我們可以通過子控件的索引的狀態存儲在一個父組件和訪問它。

相關問題