reactjs - 防止重复对象但在 shopping cart ReactJS/NextJS 中更新数量

我在 NextJS 中遇到 shopping cart 问题,当有人单击产品页面中的“添加到购物车”按钮时,我正在尝试更新购物车。我正在使用本地存储。

export const DataContext = createContext();

export const DataProvider = ({ children }) => {
  const initialState = [];
  const [cart, setCart] = useState(initialState);
  const [qty, setQty] = useState(1);

  useEffect(() => {
    const cartData = JSON.parse(localStorage.getItem("cart"));
    if (cartData) {
      setCart(cartData);
    }
  }, []);

  useEffect(() => {
    if (cart !== initialState)
      localStorage.setItem("cart", JSON.stringify(cart));

  }, [cart]);

  const addToCart = (newProduct) => {
    const ProductExists = cart.find((pr) => pr.item._id === newProduct._id);
    setCart((prev) => [...prev, { item: newProduct, quantity: 1 }]);
    // Here is where I have to solve the problem I think, obviously Im just adding a single product
   
  };


  return (
    <DataContext.Provider value={{ cart, setCart, state, dispatch, addToCart }}>
      {children}
    </DataContext.Provider>
  );
};

我希望我说清楚了 提前谢谢你。

回答1

老实说,我建议您使用 Map 或 Object 而不是数组,因为它应该如下所示:

/*
 *  {
 *    [productId1]: {
 *      quantity: Number,
 *      ...newProduct // All the other product attributes here
 *    }
 *  }
 */

const addToCart = (newProduct) => {
  const prevProduct = cart[newProduct._id];
  const prevQuatity = prevProduct.quantity || 0;
  setCart((prev) => ({
    ...prev,
    [newProduct.Id]: {
      ...newProduct,
      quantity: prevQuatity + 1,
    },
  }));
};

相似文章