How to update nested state properties in React

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

    I know it is an old question but still wanted to share how i achieved this. Assuming state in constructor looks like this:

      constructor(props) {
        super(props);
    
        this.state = {
          loading: false,
          user: {
            email: ""
          },
          organization: {
            name: ""
          }
        };
    
        this.handleChange = this.handleChange.bind(this);
      }
    

    My handleChange function is like this:

      handleChange(e) {
        const names = e.target.name.split(".");
        const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
        this.setState((state) => {
          state[names[0]][names[1]] = value;
          return {[names[0]]: state[names[0]]};
        });
      }
    

    And make sure you name inputs accordingly:

    
    
    
    

提交回复
热议问题