如何使用不变性助手更新数组中的嵌套对象? [英] how to use Immutability helper to update a nested object within an array?
问题描述
在reducer内部,给定一个状态对象:
Inside reducer, given a state object:
var state = {
"data": [{
"subset": [{
"id": 1
}, {
"id": 2
}]
}, {
"subset": [{
"id": 10
}, {
"id": 11
}, {
"id": 12
}]
}]
}
如您所见,数据是一个嵌套数组,其每个元素中都有数组.
As you can see, the data is a nested array, with arrays in each of its elements.
知道 action.indexToUpdate 将是数据的索引,我想以编程方式将 data[action.indexToUpdate].subset 更新为新数组.例如,如果 action.indexToUpdate = 0,则 data[0] 将从
Knowning that action.indexToUpdate will be a index for data, I want to update data[action.indexToUpdate].subset to a new array programmatically. For example, if action.indexToUpdate = 0, then data[0] will be updated from
[{"id":1},{"id":2}]
到
[{"id":4},{"id":5}]
为了做到这一点,我有:
In order to do so, I have:
let newSubset = [{"id":4},{"id":5}]
let newState = update(state.data[action.indexToUpdate], {
subset: {
newSubset,
},
})
但是当我执行这个时,它返回错误:
But when I executed this, it returns error:
TypeError: value is undefined
关于更新功能.
我一直在查看这里的 react ducommentation:https://facebook.github.io/react/docs/update.html 但我真的不知道该怎么做.请指教!
I have been looking at the react ducomentation here: https://facebook.github.io/react/docs/update.html but I couldn't really figure out how to do it. Please advise!
推荐答案
你的更新看起来像
var obj = {"state" : {
"data": [{
"subset": [{
"id": 1
}, {
"id": 2
}]
}, {
"subset": [{
"id": 10
}, {
"id": 11
}, {
"id": 12
}]
}]
}}
return update(obj, {
"state" : {
"data": {
[action.indexToUpdate]: {
"subset": {
$set: [newSubset]
}
}
}
}
})
如果子集中有其他字段,但您只想更改包含其他键的特定索引处的字段,您可以编写
In case there are other fields in subset, but you only wish to the change the fields at specific index containing other keys, you would write
return update(obj, {
"state" : {
"data": {
[action.indexToUpdate]: {
"subset": {
[id]: {$merge: newSubset}
}
}
}
}
})
这篇关于如何使用不变性助手更新数组中的嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!