在Reducer中使用扩展语法

问题描述 投票:-1回答:2

我试图使用spread语法来更新reducer中的状态

状态由一个对象组成,该对象有一个数组,

我想更新对象中的所有属性,除了数组,我想在最后添加下一个状态元素。例如,

例如,如果状态是

{
  id: 4,
  amount: 10,
  arr: [
    name: "peter",
    name: "john"
  ]
}

和行动

{
  id: 7,
  amount: 7,
  arr: [
    name: "sally",
    name: "maria"
  ]
}

我希望得到使用扩展语法的结果

{
  id: 7,
  amount: 7,
  arr: [
    name: "peter",
    name: "john",
    name: "sally",
    name: "maria"
  ]
}

获取动作的id和数量,并连接数组

谢谢

javascript reactjs redux spread-syntax
2个回答
2
投票

只需保持传播道具。

  1. 传播你现在的状态
  2. 传播行动的有效载荷
  3. 根据需要更改属性

const INITIAL_STATE = {
  id: 4,
  amount: 10,
  arr: [
    { name: "peter" },
    { name: "john" },
  ],
}

function reducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    default: return state
    case 'ANY_ACTION': 
      return {
        ...state,
        ...action.payload,
        arr: [
          ...(state.arr || []),
          ...action.payload.arr,
        ]
      }
  }
}

const action = {
  type: 'ANY_ACTION',
  payload: {
    id: 7,
    amount: 7,
    arr: [
      { name: "sally" },
      { name: "maria" },
    ]
  }
}

const state = reducer(undefined, action)
console.log(state)

1
投票

首先你的结构是无效的,正确的结构看起来像

{
  id: 4,
  amount: 10
  data: [
    {name: "peter"},
    {name: "john"}
  ]
}

然后你可以使用扩展运算符来更新状态,假设action.payload

{
  id: 7,
  amount: 7
  data: [
    {name: "sally"},
    {name: "maria"}
  ]
}

喜欢

case 'WHATEVER_ACTION': 
   return {
        ...state,
        id: action.payload.id,
        amount: action.payload.amount,
        data: [...state.data, ...action.payload.data]
   }

查看Spread syntax的文档以了解其用法

© www.soinside.com 2019 - 2024. All rights reserved.