You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit报错:cart切片reducer初始化时返回undefined

问题根因

报错原因是cart切片在初始化阶段返回了undefined状态,核心是编写createSlice配置时的拼写错误,另外还有3个会触发后续异常的隐患:

  • 核心触发点:createSlice配置项中定义初始状态的合法字段为*initialState*,你错写为initialValue,Redux Toolkit无法识别到初始状态,初始化时传入reducer的state为undefined,直接触发报错。
  • 配置隐患:你当前默认导出的是整个cartSlice对象,在store入口文件中挂载时必须取它的.reducer属性作为reducer函数传入,不能直接把整个slice对象当reducer配置。
  • 运行时隐患:你定义的removeFromCart reducer目前是空函数,后续触发对应action时极易返回undefined触发同类报错。
  • 逻辑错误:addToCart已存在商品的分支中,你错把单品单价做累加,且没有更新全局购物车商品总数,会导致金额、数量计算错误。
修复步骤
  1. 将cartSlice.js中的initialValue字段名修正为initialState
  2. 补全removeFromCart的处理逻辑,避免空函数导致的异常
  3. 修正购物车金额、总数的累加逻辑
  4. 检查store入口配置,确保挂载的是切片的reducer属性而非整个slice对象
修正后的cartSlice.js代码
import { createSlice } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  // 修正字段名拼写错误
  initialState: { itemsList: [], totalQuantity: 0, showCart: false },
  reducers: {
    addToCart(state, action) {
      const newItem = action.payload;
      const existingItem = state.itemsList.find((item) => item.id === newItem.id);

      if (existingItem) {
        existingItem.quantity++;
        existingItem.totalPrice += newItem.price;
        state.totalQuantity++;
      } else {
        state.itemsList.push({
          id: newItem.id,
          price: newItem.price,
          quantity: 1,
          totalPrice: newItem.price,
          name: newItem.name,
        });
        state.totalQuantity++;
      }
    },

    // 补全移除购物车商品逻辑
    removeFromCart(state, action) {
      const targetId = action.payload;
      const existingItem = state.itemsList.find(item => item.id === targetId);
      if (existingItem.quantity === 1) {
        state.itemsList = state.itemsList.filter(item => item.id !== targetId);
      } else {
        existingItem.quantity--;
        existingItem.totalPrice -= existingItem.price;
      }
      state.totalQuantity--;
    },
    setShowCart(state) {
      state.showCart = !state.showCart;
    },
  },
});

export const cartActions = cartSlice.actions;
// 直接导出reducer,store引入更方便
export default cartSlice.reducer;
store入口配置参考
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';

const store = configureStore({
  reducer: {
    cart: cartReducer
  }
});

export default store;

修改完成后刷新页面,初始化报错会直接消失,购物车的加减、显隐逻辑也可正常运行。

内容的提问来源于stack exchange,提问作者Dalibor Pavlik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 07:42:15