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

后端 未结 4 1318
甜味超标
甜味超标 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:26

    I made a util function that updates nested states with dynamic keys.

     function _recUpdateState(state, selector, newval) {
              if (selector.length > 1) {
                let field = selector.shift();
                let subObject = {};
                try {
                  //Select the subobject if it exists
                  subObject = { ..._recUpdateState(state[field], selector, newval) };
                } catch {
                  //Create the subobject if it doesn't exist
                  subObject = {
                    ..._recUpdateState(state, selector, newval)
                  };
                }
                return { ...state, [field]: subObject };
              } else {
                let updatedState = {};
                updatedState[selector.shift()] = newval;
                return { ...state, ...updatedState };
              }
            }
            
            function updateState(state, selector, newval, autoAssign = true) {
              let newState = _recUpdateState(state, selector, newval);
              if (autoAssign) return Object.assign(state, newState);
              return newState;
            }
            
    // Example
    
    let initState = {
           sub1: {
              val1: "val1",
              val2: "val2",
              sub2: {
                 other: "other value",
                 testVal: null
              }
           }
        } 
        
        console.log(initState)
        updateState(initState, ["sub1", "sub2", "testVal"], "UPDATED_VALUE")
        console.log(initState)

    You pass a state along with a list of key selectors and the new value.

    You can also set the autoAssign value to false to return an object that is a copy of the old state but with the new updated field - otherwise autoAssign = true with update the previous state.

    Lastly, if the sequence of selectors don't appear in the object, an object and all nested objects with those keys will be created.

提交回复
热议问题