防止重复对象但更新购物车中的数量 ReactJS/NextJS

Prevent duplicate objects but update quantity in shopping cart ReactJS/NextJS

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

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>
  );
};

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

老实说,出于这个原因,我建议您使用 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,
    },
  }));
};