首页 文章

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

提问于
浏览
1

我从我的API获取数据,并在将其转储到redux之前将其传递给normalizr . 当我从API获取人员数据时,reducer应将它们附加到人员商店 . 现在我的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
  }
}

第一个控制台日志是减速器使用一次后的状态 . 它有我保存到商店的最初一组人:

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

那么第三个控制台日志应该是两个状态的组合?但它只是用sally和ana重复最后一个,并覆盖其他所有内容 .

1 回答

  • 2

    那是因为传播不会递归地组合对象 .

    看看这个简单的例子,它按预期工作:

    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)
    

相关问题