Reducer Dispatch 推送问题

Reducer Dispatch Push Issue

有人可以看看我的减速器,看看 .push() 有什么问题吗?由于某种原因,抛出以下错误

error TypeError: Cannot read properties of undefined (reading 'push')

但该值并非未定义。

Cart Reducer State = {"cartItems":[],"itemCount":0,"total":0}
Cart Reducer Action = {"type":"ADD_ITEM","payload":{"_id":"61cb88d85f499fd4563e99d3","sku":1001,"image":"blueband","title":"Wrist Band - 1 Custom Insert","description":"Band with custom photo insert included with purchase.","active":{"status":true,"display":true,"startDate":"2021-09-21T22:55:03.686Z","endDate":""},"color":"Blue","quantity":100,"price":16.99,"createdAt":"2021-12-28T21:59:52.357Z","updatedAt":"2021-12-28T21:59:52.357Z","__v":0}}
export const sumItems = (cartItems) => {
  return {
    itemCount: cartItems.reduce((total, prod) => total + prod.quantity, 0),
    total: cartItems.reduce(
      (total, prod) => total + prod.price * prod.quantity,
      0
    ),
  };
};

const cartReducer = (state, action) => {
  switch (action.type) {
    case "ADD_ITEM":
      //check if item is in cart
      if (!state.cartItems.find((item) => item._id === action.payload._id)) {
        //Below is an Object
        console.log(JSON.stringify(state));
        console.log(JSON.stringify(action));
        state.cartItem.push({
          ...action.payload,
          quantity: 1,
        });
      }
      return {
        ...state,
        cartItems: [...state.cartItems],
        ...sumItems(state.cartItems),
      };
    default:
      return state;
  }
};

export default cartReducer;

您需要为减速器提供初始状态。 您目前 returning statedefault 情况下,最初将是 undefined (检查 redux-dev 工具)。

在你的 reducer 定义中,为 state 参数设置一个默认值,像这样 state = {cartItems: [], itemCount: 0, total: 0}

或者您可以移动文件中的初始状态,例如 state.js,内容如下:

export default {
  cartItems: [],
  itemCount: 0,
  total: 0
}

然后将其导入您的减速器中:

import initialState from './state';

并通过参数的默认值或 default 案例中的 return initalState 在你的 reducer 中设置 initialState

default: 
  return initialState;