购物车商品重复添加问题:存在商品时未更新数量反而新增
购物车商品重复添加问题修复
问题根源
你的代码存在三个关键问题导致商品重复添加:
- map方法未返回非匹配项:当商品已存在时,
map遍历仅返回了匹配的商品对象,未匹配的项没有返回,导致updatedCartItems数组中出现undefined,破坏了购物车数据结构,最终触发异常逻辑。 - 状态与localStorage数据不同步:else分支中使用
cartItems而非cartItemsFromLocalStorage拼接新数组,可能导致新旧数据不一致。 - 直接修改原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
相关产品推荐
相关产品推荐

