Clearing state es6 React

前端 未结 13 865
独厮守ぢ
独厮守ぢ 2020-12-07 13:04

I am trying to clear a components state but can\'t find a reference for the es6 syntax. I was using:

this.replaceState(this.getInitialState());

13条回答
  •  半阙折子戏
    2020-12-07 13:54

    This is how I handle it:

    class MyComponent extends React.Component{
      constructor(props){
        super(props);
        this._initState = {
            a: 1,
            b: 2
          }
        this.state = this._initState;
      }
    
      _resetState(){
         this.setState(this._initState);
       }
    }
    

    Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.

提交回复
热议问题