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

Redux-Toolkit createSlice reducer计数递增异常问题求助

问题分析与修复

核心问题

你的代码存在几个关键问题导致count无法正确递增:

  1. 修改了快照而非草稿状态
    你使用current(state.items)获取状态的只读快照,对快照中item的修改不会被Immer追踪,因此无法同步到实际的Redux状态中。

  2. 对象引用比较错误
    item === action.payload是通过对象引用判断是否为同一件商品,但每次触发action时传入的payload可能是新创建的对象(即使内容相同),导致比较失败。应该使用商品的唯一标识(如id)来判断。

  3. 不必要的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:17:06