How to update nested state properties in React

后端 未结 26 1989
野趣味
野趣味 2020-11-21 06:35

I\'m trying to organize my state by using nested property like this:

this.state = {
   someProperty: {
      flag:true
   }
}

But updating

26条回答
  •  孤独总比滥情好
    2020-11-21 07:18

    If you are using ES2015 you have access to the Object.assign. You can use it as follows to update a nested object.

    this.setState({
      someProperty: Object.assign({}, this.state.someProperty, {flag: false})
    });
    

    You merge the updated properties with the existing and use the returned object to update the state.

    Edit: Added an empty object as target to the assign function to make sure the state isn't mutated directly as carkod pointed out.

提交回复
热议问题