在redux存储中更新嵌套数据 [英] Updating nested data in redux store
问题描述
使用redux更新商店中嵌套数据的最佳/正确方法是什么?
What's the best/correct way to update a nested array of data in a store using redux?
我的商店看起来像这样:
My store looks like this:
{
items:{
1: {
id: 1,
key: "value",
links: [
{
id: 10001
data: "some more stuff"
},
...
]
},
...
}
}
我有一对异步操作,用于更新完整的 items
对象,但是我还有另外一对操作要更新特定的链接
数组。
I have a pair of asynchronous actions that updates the complete items
object but I have another pair of actions that I want to update a specific links
array.
我的减速机目前看起来像这样,但我不确定这是否是正确的方法:
My reducer currently looks like this but I'm not sure if this is the correct approach:
switch (action.type) {
case RESOURCE_TYPE_LINK_ADD_SUCCESS:
// TODO: check whether the following is acceptable or should we create a new one?
state.items[action.resourceTypeId].isSourceOf.push(action.resourceTypeLink);
return Object.assign({}, state, {
items: state.items,
});
}
推荐答案
React的 update()
immutability helper 是创建更新版本的便捷方式一个普通的旧JavaScript对象而不会改变它。
React's update()
immutability helper is a convenient way to create an updated version of a plain old JavaScript object without mutating it.
你给它一个要更新的源对象和一个描述需要更新的部分的路径的对象并改变它需要制作。
You give it the source object to be updated and an object describing paths to the pieces which need to be updated and changes that need to be made.
例如,如果一个动作有 id
和链接
属性,您希望将链接
推送到以 id
:
e.g., if an action had id
and link
properties and you wanted to push the link
to an array of links in an item keyed with the id
:
var update = require('react/lib/update')
// ...
return update(state, {
items: {
[action.id]: {
links: {$push: action.link}
}
}
})
(示例使用ES6计算属性 action.id
)
(Example uses an ES6 computed property name for action.id
)
这篇关于在redux存储中更新嵌套数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!