传播运算符覆盖新对象中的元素而不是组合

Spread operator overwriting elements in new object instead of combining

我正在从我的 API 获取数据,并在将其转储到 redux 之前将其传递给 normalizr。当我从 API 获取人员数据时,reducer 应该将它们附加到人员存储中。现在我的减速器正在覆盖商店中的所有现有数据。

减速器:

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
  }
}

这第一个console log是reducer使用一次后的状态。它有我保存到商店的最初一组人:

{ 
    entities: { 
                people : { 
                          1 : { id: 1, name: "jim" },
                          2 : { id: 2, name: "billy" }
                         }
              },
    result : [ 1, 2 ]
}

第二个控制台日志将是要添加的新人的负载:

{ 
    entities: { 
                people : { 
                          7 : { id: 7, name: "sally" },
                          8 : { id: 8, name: "ana" }
                         }
              },
    result : [ 7, 8 ]
}

那么第三个console log应该是两种状态合并吧?但它只是用 sally 和 ana 重复最后一个,并覆盖其他所有内容。

那是因为 spread 不会递归地组合对象。

看一下这个简单的示例,它的工作原理与您预期的一样:

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)