What's the best alternative to update nested React state property with setState()?

后端 未结 4 1307
甜味超标
甜味超标 2021-02-08 08:45

I\'ve been thinking about what would be the best way among these options to update a nested property using React setState() method. I\'m also opened to more efficient methods co

4条回答
  •  感情败类
    2021-02-08 09:12

    You can try with nested Object.Assign:

     const newState = Object.assign({}, state, {
      inputs: Object.assign({}, state.inputs, {
        username: Object.assign({}, state.inputs.username, { touched: true }),
      }),
    });
    

    };

    You can also use spread operator:

    {
      ...state,
      inputs: {
        ...state.inputs,
          username: {
          ...state.inputs.username,
          touched: true
       }
    }
    

    This is proper way to update nested property and keep state immutable.

提交回复
热议问题