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

购物车商品重复添加问题:存在商品时未更新数量反而新增

购物车商品重复添加问题修复

问题根源

你的代码存在三个关键问题导致商品重复添加:

  1. map方法未返回非匹配项:当商品已存在时,map遍历仅返回了匹配的商品对象,未匹配的项没有返回,导致updatedCartItems数组中出现undefined,破坏了购物车数据结构,最终触发异常逻辑。
  2. 状态与localStorage数据不同步:else分支中使用cartItems而非cartItemsFromLocalStorage拼接新数组,可能导致新旧数据不一致。
  3. 直接修改原product对象:直接赋值product.quantity会修改原始数据对象,不符合不可变数据的原则,可能引发其他潜在问题。

修正后的代码

// Adding Items to cart
const onAdd = (product, quantity) => {
  const checkProductInCart = cartItemsFromLocalStorage.find((item) => item.id === product.id);

  setTotalPrice((prevTotalPrice) => (prevTotalPrice + Math.round((product.price * quantity)*100)/100));
  setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);

  if(checkProductInCart) {
    const updatedCartItems = cartItemsFromLocalStorage.map((cartProduct) => {
      if(cartProduct.id === product.id) {
        return {
          ...cartProduct,
          quantity: cartProduct.quantity + quantity
        }
      }
      // 必须返回原对象,否则数组会出现undefined
      return cartProduct;
    });

    setCartItems(updatedCartItems);
  } else {
    // 不修改原product,创建新对象添加数量属性
    const newCartItem = {
      ...product,
      quantity: quantity
    };
    // 使用localStorage的数据拼接新数组,保证数据一致
    setCartItems([newCartItem, ...cartItemsFromLocalStorage]);
  }

  toast.success(` ${product.name} added to the cart.`);
};

关键修改说明

  • 修复map遍历:为非匹配的商品对象添加return cartProduct,确保数组结构完整。
  • 替换拼接数据源:else分支中用cartItemsFromLocalStorage代替cartItems,保证购物车数据与本地存储同步。
  • 避免修改原对象:通过展开运算符创建新的购物车项对象,添加quantity属性,不污染原始product数据。

内容的提问来源于stack exchange,提问作者Ons Jannet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:10:26