【问题标题】:How to update cart quantity if item already exist in Cart - reactjs?如果购物车中已经存在商品 - reactjs,如何更新购物车数量?
【发布时间】:2021-01-12 21:08:28
【问题描述】:

在此代码中,而不是显示“产品已添加到购物车”。提示信息,如果购物车中已经存在商品,我想更新购物车数量,请帮帮我。

const addToCart = (id) => {
    const check = cart.every((item) => {
      return item.id !== id;
    });
    if (check) {
      const cartData = products.filter((el) => {
        return el.id === id;
      });
      setCart([...cart, ...cartData]);
    } else {
      alert('The product has been added to cart.');
    }

【问题讨论】:

  • 你能添加 cartData 架构吗?
  • 为什么不直接使用cart.find(item => item.id === id)?

标签: javascript arrays reactjs react-hooks


【解决方案1】:

我在这里对您的变量的外观做出一些假设,但一般来说,这是您需要的:

const products = [{id: 1, name: 'Prod 1'}, {id: 2, name: 'Prod 2'}, {id: 3, name: 'Prod 3'}, {id: 4, name: 'Prod 4'}]
const cart = [{id: 1, name: 'Prod 1', quantity: 1}, {id: 4, name: 'Prod 4', quantity: 1}];

const addToCart = (id) => {
    const check_index = cart.findIndex(item => item.id === id);
    if (check_index !== -1) {
      cart[check_index].quantity++;
      console.log("Quantity updated:", cart);
    } else {
      cart.push({...products.find(p => p.id === id), quantity: 1})
      console.log('The product has been added to cart:', cart);
    }
}

addToCart(4)

【讨论】:

    【解决方案2】:

    尝试类似于下面的方法:

       const addToCart = (id) => {
      const check = cart.every((item) => {
        return item.id !== id;
      });
      const cartData = products.filter((el) => {
        return el.id === id;
      });
      if (check) {
        setCart([...cart, ...cartData]);
      } else {
        const itemForCountIncrease = cart.find((item) => item.id == id);
        itemForCountIncrease.count += 1;
        setCart([...cart.filter((item) => item.id != id), itemForCountIncrease]);
      }
    };
    

    【讨论】:

    • 现在当我添加相同的产品时数量会增加,但是数量会增加,例如 1 然后 2 然后 4 然后 8 然后 16 然后 32 ...
    • 上述方法的问题是你设置了一个只增加1的约束。如果你想添加多个产品怎么办?此外,我不得不做出一些假设,因为我不知道您的项目结构以及您如何使用产品
    • 非常感谢......它工作得非常好,还有一件事,我正在向 localStorage 添加购物车价值......在页面刷新时,产品仍然在购物车中,但产品被添加为新的如果我再次添加相同的产品,产品在购物车中,所以我想检查 AddToCart 功能是否 localStorage 有这个值并且应该只更新数量,这里是 localstorage 代码useEffect(() => { localStorage.setItem('dataCart', JSON.stringify(cart)); }, [cart]); const initialCart = JSON.parse(localStorage.getItem('dataCart')) || []; const [cart, setCart] = useState(initialCart);
    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多