How to update nested state properties in React

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

    Although you asked about a state of class-based React component, the same problem exists with useState hook. Even worse: useState hook does not accept partial updates. So this question became very relevant when useState hook was introduced.

    I have decided to post the following answer to make sure the question covers more modern scenarios where the useState hook is used:

    If you have got:

    const [state, setState] = useState({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })
    

    you can set the nested property by cloning the current and patching the required segments of the data, for example:

    setState(current => { ...current, someProperty: { ...current.someProperty, flag: false } });
    

    Or you can use Immer library to simplify the cloning and patching of the object.

    Or you can use Hookstate library (disclaimer: I am an author) to simply the management of complex (local and global) state data entirely and improve the performance (read: not to worry about rendering optimization):

    import { useStateLink } from '@hookstate/core' 
    const state = useStateLink({ someProperty: { flag: true, otherNestedProp: 1 }, otherProp: 2 })
    

    get the field to render:

    state.nested.someProperty.nested.flag.get()
    // or 
    state.get().someProperty.flag
    

    set the nested field:

    state.nested.someProperty.nested.flag.set(false)
    

    Here is the Hookstate example, where the state is deeply / recursively nested in tree-like data structure.

提交回复
热议问题