Redux Toolkit报错:cart切片reducer初始化时返回undefined
问题根因
报错原因是cart切片在初始化阶段返回了undefined状态,核心是编写createSlice配置时的拼写错误,另外还有3个会触发后续异常的隐患:
- 核心触发点:
createSlice配置项中定义初始状态的合法字段为*initialState*,你错写为initialValue,Redux Toolkit无法识别到初始状态,初始化时传入reducer的state为undefined,直接触发报错。 - 配置隐患:你当前默认导出的是整个
cartSlice对象,在store入口文件中挂载时必须取它的.reducer属性作为reducer函数传入,不能直接把整个slice对象当reducer配置。 - 运行时隐患:你定义的
removeFromCartreducer目前是空函数,后续触发对应action时极易返回undefined触发同类报错。 - 逻辑错误:
addToCart已存在商品的分支中,你错把单品单价做累加,且没有更新全局购物车商品总数,会导致金额、数量计算错误。
修复步骤
- 将
cartSlice.js中的initialValue字段名修正为initialState - 补全
removeFromCart的处理逻辑,避免空函数导致的异常 - 修正购物车金额、总数的累加逻辑
- 检查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
相关产品推荐
相关产品推荐

