How to update nested state properties in React

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

    Although nesting isn't really how you should treat a component state, sometimes for something easy for single tier nesting.

    For a state like this

    state = {
     contact: {
      phone: '888-888-8888',
      email: 'test@test.com'
     }
     address: {
      street:''
     },
     occupation: {
     }
    }
    

    A re-useable method ive used would look like this.

    handleChange = (obj) => e => {
      let x = this.state[obj];
      x[e.target.name] = e.target.value;
      this.setState({ [obj]: x });
    };
    

    then just passing in the obj name for each nesting you want to address...

    
    

提交回复
热议问题