通过reducer将项添加到子对象的子对象中的数组

时间:2018-03-31 01:11:15

标签: reactjs redux react-redux

如果我的术语不正确,我道歉。我对reactjs和react-redux(几天)都很新。

我想要克服的挑战是在store.order.cart.items中添加一个项目。我的商店结构是这样的:

{
    order:
        cart:
            items: [
                {name: "product a"},
                {name: "product b"}
            ]
}

我的减速机如下:

import ApplicationState from '../application-state';
import { ADD_PRODUCT } from "../constants/action-types";

const initialState = ApplicationState;

const rootReducer = (state = initialState, action) => {

  switch (action.type) {
    case ADD_PRODUCT:
        return {
            ...state, order: {
                ...state.order, cart: {
                    ...state.cart, items: [
                        ...state.items, action.payload
                    ]
                }
            }
        };
    default:
      return state;
  }
};

export default rootReducer;

我对ADD_PRODUCT的行动如下:

import { ADD_PRODUCT } from "../constants/action-types"

export const addProduct = product => ({ type: ADD_PRODUCT, payload: product });

我的动作类型常量(常量/动作类型):

export const ADD_PRODUCT = "ADD_PRODUCT";

当我发送addProduct操作时(通过浏览器控制台测试:store.dispatch( addProduct({ name: "product c" }) )

我收到以下错误:

app.js:36995 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.from (/native)
    at _toConsumableArray (app.js:36995)
    at rootReducer (app.js:37009)
    at Object.dispatch (app.js:13839)
    at <anonymous>:1:7

我做错了什么?将新项目添加到order.cart.items数组的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

items: [
  ...state.items, action.payload
]

在上面的摘录中,您试图将...state.items传播到items数组中,但项目实际上是state.order.cart.items;

类似地:

cart: {
  ...state.cart, 
}

cart实际上是state.order.cart

这种深度嵌套的情况是为什么最好在可能的情况下展平您的状态并使用combineReducers()。或者,您可以查看不变性助手,以帮助不可变地设置深层嵌套状态