How to update nested state properties in React

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

    I used this solution.

    If you have a nested state like this:

       this.state = {
              formInputs:{
                friendName:{
                  value:'',
                  isValid:false,
                  errorMsg:''
                },
                friendEmail:{
                  value:'',
                  isValid:false,
                  errorMsg:''
                }
    }
    

    you can declare the handleChange function that copy current status and re-assigns it with changed values

    handleChange(el) {
        let inputName = el.target.name;
        let inputValue = el.target.value;
    
        let statusCopy = Object.assign({}, this.state);
        statusCopy.formInputs[inputName].value = inputValue;
    
        this.setState(statusCopy);
      }
    

    here the html with the event listener

    
    

提交回复
热议问题