ReactJS:如何使用动态键访问和更新嵌套状态对象?

时间:2019-05-20 07:06:54

标签: javascript reactjs ecmascript-6

假设我有一个状态定义如下的组件:

this.state = {
    apple:{
        a:1,
        b:2,
    },
    mango:{
        banana : {
            a:1,
            b:2,
        }
    }
}

如果我想在自己的状态下更新嵌套对象的值,则可以使用如下所示的硬编码键进行更新:

cost temp =  { ...this.state['mango'] }
temp['banana']['a'] = 2;

this.setState({mango:temp});

如何动态更新状态对象中的嵌套值?例如,如果我使用点或数组符号表示JSON路径,该如何更新组件状态?

1 个答案:

答案 0 :(得分:2)

一种实现此目的的方法是通过Array#reduce获取嵌套对象,该对象是路径所针对的字段的父对象:

const nestedObject = path
.slice(0, -1)
.reduce((object, part) => (object === undefined ? undefined : object[part]), { ...state })

然后通过路径的最后一个键更新nestedObject的最后一个键/值:

/* Get last part of path, and update nestedObject's value for this key, to 2 */
const [pathTail] = path.slice(-1);    
nestedObject[pathTail] = 2;

以下代码片段将这两个想法结合在一起:

/* Path of nested field to update, in array notation */
const path = ['mango', 'banana', 'a'];

/* Components state */
const state = {
  apple: {
    a: 1,
    b: 2,
  },
  mango: {
    banana: {
      a: 1,
      b: 2,
    }
  }
};

const stateClone = { ...state };

/* Aquire the parent object (ie banana) of the target field (ie a) */
const nestedObject = path
.slice(0, -1)
.reduce((object, part) => (object === undefined ? undefined : object[part]), stateClone)

if (nestedObject !== undefined) {

  /* Obtain last key in path */
  const [pathTail] = path.slice(-1);

  /* Update value of last key on target object to new value */
  nestedObject[pathTail] = 2;
}

/* Display updated state */
console.log('Updated state:', stateClone)

/* Call this.setState: */
// this.setState(stateClone);

更新

这里有一些额外的细节,概述了答案的reduce()部分是如何工作的:

path
/* slice obtains ['mango', 'banana'], seeing -1 clips last item */
.slice(0, -1)  
/* reduce iterates through each part of array ['mango', 'banana']
where at each iteration we fetch the corresponding nested object 
of the { ...state } object that's passed in */
.reduce((object, part) => {

/* At iteration 1: 
object has two keys, 'apple' and 'mango'
part is 'mango'
object is defined, so return object['mango'] for first iteration

At iteration 2:
object passed from last iteration has one key, 'banana'
part is 'banana'
object is defined, so return object['banana'] for second iteration

Reduce complete:
we return object['banana'], which is the same as state['mango']['banana']
*/

if(object === undefined) { return undefined; }

return object[part]

}, stateClone)