Clearing state es6 React

前端 未结 13 838
独厮守ぢ
独厮守ぢ 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

    Problem

    The accepted answer:

    const initialState = {
        /* etc */
    };
    
    class MyComponent extends Component {
        constructor(props) {
            super(props)
            this.state = initialState;
        }
        reset() {
            this.setState(initialState);
        }
        /* etc */
    }
    

    unfortunately is not correct.

    initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.

    Solution

    You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.

提交回复
热议问题