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

如何修复React Shop Context中购物车与心愿单的操作函数?

修复购物车与心愿单功能函数问题

你的代码中购物车和心愿单函数存在逻辑错误,导致无法正确展示已添加商品,以下是针对性修复方案:

1. 调整状态初始值

首先修正状态的存储结构,让后续逻辑更清晰:

// 将cartItems改为对象,以商品id为键存储数量
const [cartItems, setCartItems] = useState({}); 
// wishlist改为对象,存储商品id与对应是否收藏的状态
const [wishlist, setWishlist] = useState({}); 

2. 修复addToCart函数

原问题:首次添加商品时,因购物车数组中无对应条目,无法创建新的购物项,导致购物车无内容。
修复后代码:

const addToCart = (id) => {
  setCartItems((prevItems) => {
    // 若商品已在购物车,数量+1;否则初始化为1
    return {
      ...prevItems,
      [id]: (prevItems[id] || 0) + 1
    };
  });
  increaseQuantityTotal();
};

3. 修复removeFromCart函数

原问题:错误通过索引访问数组元素,逻辑混乱,未处理数量归0时移除条目的情况。
修复后代码:

const removeFromCart = (id) => {
  setCartItems((prevItems) => {
    const updatedItems = { ...prevItems };
    if (updatedItems[id] > 1) {
      updatedItems[id] -= 1;
    } else {
      // 数量为0时从购物车移除该商品
      delete updatedItems[id];
    }
    return updatedItems;
  });
  decreaseQuantityTotal();
};

4. 修复addToWishlist函数

原问题:数组存储结构导致无法正确定位商品,且未处理商品不在心愿单时的初始化逻辑。
修复后代码:

const addToWishlist = (id) => {
  setWishlist((prevLists) => ({
    ...prevLists,
    [id]: true
  }));
};

5. 修复removeFromWishlist函数

原问题:数组操作逻辑错误,无法正确取消收藏状态。
修复后代码:

const removeFromWishlist = (id) => {
  setWishlist((prevLists) => ({
    ...prevLists,
    [id]: false
  }));
  // 若需要彻底移除条目,可改为delete prevLists[id]
};

6. 同步修正getTotalCartAmount函数

因为cartItems改为对象,需要对应调整计算逻辑:

const getTotalCartAmount = () => {
  let totalAmount = 0;
  Object.entries(cartItems).forEach(([productId, quantity]) => {
    const product = products.find(p => p.id === parseInt(productId));
    if (product) {
      totalAmount += quantity * product.price;
    }
  });
  const roundedTotal = Math.round(totalAmount * 100000) / 100000;
  return roundedTotal;
};

完整修复后的Context组件代码

import React, { createContext, useState } from 'react';
import useProducts from '../fetchApi/useProducts';

export const ShopContext = createContext(null);

const ShopContextProvider = ({ children }) => {
  const { isLoading, products } = useProducts();
  const [cartItems, setCartItems] = useState({});
  const [quantityTotal, setQuantityTotal] = useState(0);
  const [searchTerm, setSearchTerm] = useState("");
  const [sortBy, setSortBy] = useState('price');
  const [wishlist, setWishlist] = useState({});

  if (isLoading) {
    return "...Loading"
  }

  const sortProducts = (sortBy) => {
    const sortedProducts = [...products];
    if (sortBy === 'price') {
      sortedProducts.sort((a, b) => a.price - b.price);
    } else if (sortBy === 'title') {
      sortedProducts.sort((a, b) => a.title.localeCompare(b.title));
    } else if (sortBy === 'quantity') {
      sortedProducts.sort((a, b) => a.quantity - b.quantity);
    }
    return sortedProducts;
  };

  const increaseQuantityTotal = () => {
    setQuantityTotal((prevTotal) => prevTotal + 1);
  };
  const decreaseQuantityTotal = () => {
    setQuantityTotal((prevTotal) => {
      if (prevTotal > 0) {
        return prevTotal - 1;
      }
      return prevTotal;
    });
  };

  const handleSearch = (e) => {
    setSearchTerm(e.target.value);
  };
  
  const addToCart = (id) => {
    setCartItems((prevItems) => {
      return {
        ...prevItems,
        [id]: (prevItems[id] || 0) + 1
      };
    });
    increaseQuantityTotal();
  };

  const removeFromCart = (id) => {
    setCartItems((prevItems) => {
      const updatedItems = { ...prevItems };
      if (updatedItems[id] > 1) {
        updatedItems[id] -= 1;
      } else {
        delete updatedItems[id];
      }
      return updatedItems;
    });
    decreaseQuantityTotal();
  };

  const addToWishlist = (id) => {
    setWishlist((prevLists) => ({
      ...prevLists,
      [id]: true
    }));
  };

  const removeFromWishlist = (id) => {
    setWishlist((prevLists) => ({
      ...prevLists,
      [id]: false
    }));
  };

  const getTotalCartAmount = () => {
    let totalAmount = 0;
    Object.entries(cartItems).forEach(([productId, quantity]) => {
      const product = products.find(p => p.id === parseInt(productId));
      if (product) {
        totalAmount += quantity * product.price;
      }
    });
    const roundedTotal = Math.round(totalAmount * 100000) / 100000;
    return roundedTotal;
  };

  const contextValue = {
    cartItems,
    addToCart,
    removeFromCart,
    products,
    isLoading,
    quantityTotal,
    searchTerm,
    handleSearch,
    sortBy,
    sortProducts,
    setSortBy,
    getTotalCartAmount,
    addToWishlist,
    wishlist,
    removeFromWishlist,
  };

  return (
    <ShopContext.Provider value={contextValue}>
      {children}
    </ShopContext.Provider>
  );
};

export default ShopContextProvider;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:40:06