How to update nested state properties in React

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

    To make things generic, I worked on @ShubhamKhatri's and @Qwerty's answers.

    state object

    this.state = {
      name: '',
      grandParent: {
        parent1: {
          child: ''
        },
        parent2: {
          child: ''
        }
      }
    };
    

    input controls

    
    
    
    

    updateState method

    setState as @ShubhamKhatri's answer

    updateState(event) {
      const path = event.target.name.split('.');
      const depth = path.length;
      const oldstate = this.state;
      const newstate = { ...oldstate };
      let newStateLevel = newstate;
      let oldStateLevel = oldstate;
    
      for (let i = 0; i < depth; i += 1) {
        if (i === depth - 1) {
          newStateLevel[path[i]] = event.target.value;
        } else {
          newStateLevel[path[i]] = { ...oldStateLevel[path[i]] };
          oldStateLevel = oldStateLevel[path[i]];
          newStateLevel = newStateLevel[path[i]];
        }
      }
      this.setState(newstate);
    }
    

    setState as @Qwerty's answer

    updateState(event) {
      const path = event.target.name.split('.');
      const depth = path.length;
      const state = { ...this.state };
      let ref = state;
      for (let i = 0; i < depth; i += 1) {
        if (i === depth - 1) {
          ref[path[i]] = event.target.value;
        } else {
          ref = ref[path[i]];
        }
      }
      this.setState(state);
    }
    

    Note: These above methods won't work for arrays

提交回复
热议问题