问题描述
我正在从我的API中获取数据,并在将其转储到redux之前将其通过normalizr传递.当我从API获取人员数据时,reducer应该将其附加到人员存储中.现在,我的reducer会覆盖商店中的所有现有数据.
I'm getting data from my API, and passing it through normalizr before dumping it into redux. When I get people data from the API the reducer should append them to the people store. Right now my reducer is overwriting all existing data in the store.
减速器:
export default function reducer(state={
people: {
entities : {
people: {
0 : {
name : ''
}
}
},
result : [0,]
}
}, action) {
switch (action.type) {
case "GET_PEOPLE": {
const newpPeople = {...state.people, ...action.payload };
console.log(state.people)
console.log(action.payload)
console.log(newpPeople)
return {...state, people : newpPeople};
}
default :
return state
}
}
此第一个控制台日志是reducer一次使用后的状态.它具有我已保存到商店中的最初一组人员:
This first console log is the state after the reducer has been used once. it has the initial set of people that i've saved to the store:
{
entities: {
people : {
1 : { id: 1, name: "jim" },
2 : { id: 2, name: "billy" }
}
},
result : [ 1, 2 ]
}
第二个控制台日志将是要添加的新人员的有效负载:
The second console log will be the payload of new people to be added:
{
entities: {
people : {
7 : { id: 7, name: "sally" },
8 : { id: 8, name: "ana" }
}
},
result : [ 7, 8 ]
}
然后,第三个控制台日志应该将两个状态组合在一起?但这只是用sally和ana重复了最后一个,并覆盖了其他所有内容.
Then the third console log should be the two states combined? But it just repeats the last one with sally and ana, and overwrites everything else.
推荐答案
这是因为散播不会递归合并对象.
That's because spread will not combine the objects recursively.
看看这个简单的示例,它可以按预期工作:
Take a look at this simple example where it works as you expected:
const state = {
entities: {
people : {
1 : { id: 1, name: "jim" },
2 : { id: 2, name: "billy" }
}
},
result : [ 1, 2 ]
}
const payload = {
entities: {
people : {
7 : { id: 7, name: "sally" },
8 : { id: 8, name: "ana" }
}
},
result : [ 7, 8 ]
}
const new_state = {
entities: {
people : {
...state.entities.people,...payload.entities.people
}
},
result : [...state.result,...payload.result]
}
console.log(new_state)
这篇关于在新对象中传播运算符覆盖元素,而不是合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!