React Redux-更新嵌套数组的状态 [英] React redux - updating nested array in state
问题描述
我在React Redux中尝试一些应用程序,并且在状态下更新(推送,删除,更新)嵌套数组时遇到问题.
I'm trying some app in react redux and i have a problem with updating (push, remove, update) the nested array in state.
我有一些叫做service的对象,像这样:
I have some object called service like this:
{
name: 'xzy',
properties: [
{ id: 1, sName: 'xxx'},
{ id: 2, sName: 'zzz'},
]
}
我在带有属性集合的化简器中所做的任何操作(在向集合中添加属性的情况下)都会产生问题,即所有属性都具有与我最近添加的最后一个属性相同的值->添加的属性对象位于服务属性集合中,但是操作替换此集合中所有属性中的所有值. 我的减速器:
Whatever I did (in case of adding property to collection) in the reducer with the properties collection generate problem that all properties got same values as the last I had recently added -> Added property object is in service properties collection but the action replace all values in all properties in this collection. My reducer:
export function service(state = {}, action) {
switch (action.type) {
case 'ADD_NEW_PROPERTY':
console.log(action.property) // correct new property
const service = {
...state, properties: [
...state.properties, action.property
]
}
console.log(service); // new property is pushed in collection but all properties get same values
return service
default:
return state;
}
}
我尝试了使用不可变性帮助程序库的一些解决方案,它产生了相同的问题:
I have tried some solution with immutability-helper library and it generate the same problem:
export function service(state = {}, action) {
case 'ADD_NEW_PROPERTY':
return update(state, {properties: {$push: [action.property]}})
default:
return state;
}
例如,当我在上面的示例中添加新属性{ id: 1, sName: 'NEW'}
时,我将获得以下状态:
For example when I add new property { id: 1, sName: 'NEW'}
to example above I will get this state:
{
name: 'xzy',
properties: [
{ id: 1, sName: 'NEW'},
{ id: 1, sName: 'NEW'},
{ id: 1, sName: 'NEW'}
]
}
有人可以帮忙吗? :)
Can someone help? :)
推荐答案
还要复制action.property
.无论调度此操作是什么,它都可能会重用同一对象.
Make a copy of action.property
as well. Whatever is dispatching this action, it could be reusing the same object.
export function service(state = {}, action) {
switch (action.type) {
case 'ADD_NEW_PROPERTY':
console.log(action.property) // correct new property
const service = {
...state,
properties: [
...state.properties,
{ ...action.property }
]
}
console.log(service); // new property is pushed in collection but all properties get same values
return service
default:
return state;
}
}
这篇关于React Redux-更新嵌套数组的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!