Redux-Toolkit createSlice reducer计数递增异常问题求助
问题分析与修复
核心问题
你的代码存在几个关键问题导致count无法正确递增:
修改了快照而非草稿状态
你使用current(state.items)获取状态的只读快照,对快照中item的修改不会被Immer追踪,因此无法同步到实际的Redux状态中。对象引用比较错误
item === action.payload是通过对象引用判断是否为同一件商品,但每次触发action时传入的payload可能是新创建的对象(即使内容相同),导致比较失败。应该使用商品的唯一标识(如id)来判断。不必要的map遍历
使用map遍历数组是为了转换元素,不适合用于查找并修改现有元素,find方法更高效且语义更清晰。
修复后的代码
import { createSlice } from "@reduxjs/toolkit"; const cartSlice = createSlice({ name: "cart", initialState: { items: [], }, reducers: { addItem: (state, action) => { // 通过商品唯一ID查找现有项 const existingItem = state.items.find( item => item.card.info.id === action.payload.card.info.id ); if (existingItem) { // 直接修改草稿状态中的count existingItem.card.info.count += 1; console.log("Count after increment:", existingItem.card.info.count); } else { // 添加新商品时初始化count为1 const newItem = { ...action.payload }; newItem.card.info.count = 1; state.items.push(newItem); } }, removeItem: (state, action) => { state.items.pop(); }, clearCart: (state, action) => { state.items.length = 0; }, }, }); export const { addItem, removeItem, clearCart } = cartSlice.actions; export default cartSlice.reducer;
修复说明
- 直接操作草稿状态:移除
current()调用,直接对state.items进行操作,Immer会自动追踪所有修改并生成不可变的新状态。 - 使用唯一标识判断重复:通过
item.card.info.id(假设商品有id属性)判断是否为同一件商品,避免引用比较的问题。 - 初始化新商品的count:添加新商品时主动将count设为1,确保后续递增正常工作。
- 使用find方法:高效定位现有商品,避免不必要的遍历。
内容的提问来源于stack exchange,提问作者Shakti Raj Singh
相关产品推荐
相关产品推荐

