Clearing state es6 React

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

    You can clone your state object, loop through each one, and set it to undefined. This method is not as good as the accepted answer, though.

    const clonedState = this.state;
    
    const keys = Object.keys(clonedState);
    keys.forEach(key => (clonedState[key] = undefined));
    
    this.setState(clonedState);
    

提交回复
热议问题