How to update nested state properties in React

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

    We use Immer https://github.com/mweststrate/immer to handle these kinds of issues.

    Just replaced this code in one of our components

    this.setState(prevState => ({
       ...prevState,
            preferences: {
                ...prevState.preferences,
                [key]: newValue
            }
    }));
    

    With this

    import produce from 'immer';
    
    this.setState(produce(draft => {
        draft.preferences[key] = newValue;
    }));
    

    With immer you handle your state as a "normal object". The magic happens behind the scene with proxy objects.

提交回复
热议问题