在Reducer中使用扩展语法

时间:2018-01-11 09:25:15

标签: javascript reactjs redux spread-syntax

我正在尝试使用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和数量,并连接数组

谢谢

2 个答案:

答案 0 :(得分:2)

只需继续传播道具。

  1. 展开你现在的状态
  2. 传播行动的有效载荷
  3. 根据需要更改属性
  4. 
    
    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 :(得分:1)

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

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

然后您可以使用spread运算符更新状态,假设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 的文档,了解其用途