Clearing state es6 React

前端 未结 13 874
独厮守ぢ
独厮守ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 13:46

    In some circumstances, it's sufficient to just set all values of state to null.

    If you're state is updated in such a way, that you don't know what might be in there, you might want to use

    this.setState(Object.assign(...Object.keys(this.state).map(k => ({[k]: null}))))
    

    Which will change the state as follows

    {foo: 1, bar: 2, spam: "whatever"} > {foo: null, bar: null, spam: null}
    

    Not a solution in all cases, but works well for me.

提交回复
热议问题