How to update nested state properties in React

后端 未结 26 1970
野趣味
野趣味 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:34

    Here's a variation on the first answer given in this thread which doesn't require any extra packages, libraries or special functions.

    state = {
      someProperty: {
        flag: 'string'
      }
    }
    
    handleChange = (value) => {
      const newState = {...this.state.someProperty, flag: value}
      this.setState({ someProperty: newState })
    }
    

    In order to set the state of a specific nested field, you have set the whole object. I did this by creating a variable, newState and spreading the contents of the current state into it first using the ES2015 spread operator. Then, I replaced the value of this.state.flag with the new value (since I set flag: value after I spread the current state into the object, the flag field in the current state is overridden). Then, I simply set the state of someProperty to my newState object.

提交回复
热议问题