How to update nested state properties in React

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

    I do nested updates with a reduce search:

    Example:

    The nested variables in state:

    state = {
        coords: {
            x: 0,
            y: 0,
            z: 0
        }
    }
    

    The function:

    handleChange = nestedAttr => event => {
      const { target: { value } } = event;
      const attrs = nestedAttr.split('.');
    
      let stateVar = this.state[attrs[0]];
      if(attrs.length>1)
        attrs.reduce((a,b,index,arr)=>{
          if(index==arr.length-1)
            a[b] = value;
          else if(a[b]!=null)
            return a[b]
          else
            return a;
        },stateVar);
      else
        stateVar = value;
    
      this.setState({[attrs[0]]: stateVar})
    }
    

    Use:

    
    

提交回复
热议问题