Clearing state es6 React

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

    I will add to the above answer that the reset function should also assign state like so:

    reset() {
      this.state = initialState;
      this.setState(initialState);
    }
    

    The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState({}) after the assignment.

提交回复
热议问题