当数组尚不存在时,如何在Redux的reducer中向数组添加元素?

问题描述 投票:0回答:1

我有一个代码沙箱来演示Redux和React遇到的问题。

https://codesandbox.io/s/reactredux-3edy8

基本上该减速器不起作用:

const initialState = {
  byId: {}
};

function addReducer(state = initialState, action) {
  switch (action.type) {
    case "RECEIVE_DATA":
      return {
        ...state,
        byId: {
          ...state.byId,
          [action.payload.id]: [
            ...state.byId[action.payload.id],
            action.payload.data
          ]
        }
      };
    default:
      return state;
  }
}

export default addReducer;

这里是动作:

import { RECEIVE_DATA } from "./actionTypes";

export function action() {
  return {
    type: RECEIVE_DATA,
    payload: {
      id: Math.floor(Math.random() * 2),
      data: Math.floor(Math.random() * 10000)
    }
  };
}

在我自己的应用中,它会抛出类似state.byId[action.payload.id] is not iterable的错误,这是正确的。但是,由于不知道ID,如何将值推入尚不存在的数组?

我以为可以通过更改initialState来解决此问题,或者也许有一个我不知道的函数允许我创建一个数组或将其推入。

javascript arrays reactjs redux
1个回答
0
投票

我不确定,但我认为您需要这样的东西

 function addReducer(state = initialState, action) {
      switch (action.type) {
        case "RECEIVE_DATA":
          return {
            ...state,
            byId: {
              ...state.byId,
              [action.payload.id]: 
                [action.payload.data]

            }
          };
        default:
          return state;
      }
    }
© www.soinside.com 2019 - 2024. All rights reserved.