How to update nested state properties in React

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

    Something like this might suffice,

    const isObject = (thing) => {
        if(thing && 
            typeof thing === 'object' &&
            typeof thing !== null
            && !(Array.isArray(thing))
        ){
            return true;
        }
        return false;
    }
    
    /*
      Call with an array containing the path to the property you want to access
      And the current component/redux state.
    
      For example if we want to update `hello` within the following obj
      const obj = {
         somePrimitive:false,
         someNestedObj:{
            hello:1
         }
      }
    
      we would do :
      //clone the object
      const cloned = clone(['someNestedObj','hello'],obj)
      //Set the new value
      cloned.someNestedObj.hello = 5;
    
    */
    const clone = (arr, state) => {
        let clonedObj = {...state}
        const originalObj = clonedObj;
        arr.forEach(property => {
            if(!(property in clonedObj)){
                throw new Error('State missing property')
            }
    
            if(isObject(clonedObj[property])){
                clonedObj[property] = {...originalObj[property]};
                clonedObj = clonedObj[property];
            }
        })
        return originalObj;
    }
    
    const nestedObj = {
        someProperty:true,
        someNestedObj:{
            someOtherProperty:true
        }
    }
    
    const clonedObj = clone(['someProperty'], nestedObj);
    console.log(clonedObj === nestedObj) //returns false
    console.log(clonedObj.someProperty === nestedObj.someProperty) //returns true
    console.log(clonedObj.someNestedObj === nestedObj.someNestedObj) //returns true
    
    console.log()
    const clonedObj2 = clone(['someProperty','someNestedObj','someOtherProperty'], nestedObj);
    console.log(clonedObj2 === nestedObj) // returns false
    console.log(clonedObj2.someNestedObj === nestedObj.someNestedObj) //returns false
    //returns true (doesn't attempt to clone because its primitive type)
    console.log(clonedObj2.someNestedObj.someOtherProperty === nestedObj.someNestedObj.someOtherProperty) 
    

提交回复
热议问题