【问题标题】:Update quantity of duplicate product in cart reactjs更新购物车reactjs中重复产品的数量
【发布时间】:2021-04-04 12:03:21
【问题描述】:

我有一辆购物车。我在点击 addToCart 时将商品添加到购物车。但是,它会添加相同商品的重复项,而不会增加其在购物车中的数量。我还有一个 incrementCountdecrementCount 用于更新购物车中添加的商品数量。我想做一个函数,既可以add to cart 也可以update the quantity in cart if item is the same

我的增量/减量也有问题 - 它会更改所有添加项目的数量,而不是我单击的特定项目。我还希望它在每次点击incrementCount/decrementCount 时更新cartTotal

这是沙盒代码 https://codesandbox.io/s/epic-night-s575k?file=/src/components/Menu.jsx

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要为购物车中的每个产品提供单独的状态变量 count。 你需要这样的组件

    Cart组件:

    import React from "react";
    import { FaTimes } from "react-icons/fa";
    
    export default function Cart({
      product,
      removeFromCart,
      count,
      incrementCount,
      decrementCount
    }) {
      const { image, title, price } = product;
    
      return (
        <>
          <li className="cart-item__container">
            <img src={image} alt={title} className="cart-item__image" />
            <h4 className="cart-item__title">{title}</h4>
            <h5 className="cart-item__price">{price}$</h5>
            <button disabled={count === 1} onClick={() => decrementCount(product)}>
              -
            </button>
            <span>{count}</span>
            <button onClick={() => incrementCount(product)}>+</button>
            <FaTimes
              className="icon__remove"
              onClick={() => removeFromCart(product)}
            ></FaTimes>
          </li>
        </>
      );
    }
    

    Menu组件:

    import React, { useState } from "react";
    
    import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
    import "react-tabs/style/react-tabs.css";
    
    import { FaShoppingCart } from "react-icons/fa";
    import products from "./products";
    import Product from "./Product";
    import Cart from "./Cart";
    
    const Menu = () => {
      const [cart, setCart] = useState([]);
    
      const addToCart = (el) => {
        const cartCopy = cart.slice();
    
        const index = cartCopy.findIndex((product) => el.id === product.id);
    
        if (index === -1) {
          cartCopy.push({ ...el, count: 1 });
        } else {
          const pr = cartCopy[index];
          cartCopy[index] = { ...pr, count: pr.count + 1 };
        }
    
        setCart(cartCopy);
      };
    
      const removeFromCart = (el) => {
        const cartCopy = cart.filter((product) => el.id !== product.id);
    
        setCart(cartCopy);
      };
    
      const decrementCount = (el) => {
        const cartCopy = cart.slice();
    
        const index = cartCopy.findIndex((product) => el.id === product.id);
    
        const pr = cartCopy[index];
        cartCopy[index] = { ...pr, count: pr.count - 1 };
    
        setCart(cartCopy);
      };
    
      const getCartTotal = () => {
        return cart.reduce(
          (total, product) => total + product.price * product.count,
          0
        );
      };
    
      const getCartCount = () => {
        // return cart.length;
        // =======OR=========
        return cart.reduce((total, product) => total + product.count, 0);
      };
    
      return (
        <>
          <Tabs className="tabs-wrapper" id="menu">
            <TabList className="tabs">
              <Tab className="tab-item">Burgers</Tab>
              <Tab className="tab-item">Lunch of the day</Tab>
              <Tab className="tab-item">Crepes</Tab>
            </TabList>
            <TabPanel>
              <div className="burgers">
                <ul>
                  {products
                    .filter((product) => product.category === "burger")
                    .map((product) => (
                      <Product
                        key={product.id}
                        product={product}
                        addToCart={addToCart}
                      />
                    ))}
                </ul>
              </div>
            </TabPanel>
            <TabPanel>
              <div className="lunch">
                <h4>Sweet lunch today!</h4>
                <span>7$</span>
                <p>
                  You can choose one of our 3 sweet crepes + one of our 4 cold
                  drinks!
                  <br />
                  Nutella crepe, Crepe with salted caramel and nuts or Oreo Bang
                  crepe with whipped cream and raspberries.
                  <br />
                  For drink - one of our homemade lemonades - Melon, Orange or
                  Lemon-Mint. Or a Frozen Coffee!
                </p>
              </div>
            </TabPanel>
            <TabPanel>
              <div className="crepes">
                <ul>
                  {products
                    .filter((product) => product.category === "crepe")
                    .map((product) => (
                      <Product
                        key={product.id}
                        product={product}
                        addToCart={addToCart}
                      />
                    ))}
                </ul>
              </div>
            </TabPanel>
          </Tabs>
          <FaShoppingCart className="cart-icon">{getCartCount()}</FaShoppingCart>
          {cart.map((el) => (
            <Cart
              key={el.id}
              product={el}
              count={el.count}
              removeFromCart={removeFromCart}
              incrementCount={addToCart}
              decrementCount={decrementCount}
            />
          ))}
          <h4 className="cart__total">Your Order Total Price: {getCartTotal()}$</h4>
          <button className="btn__clear" onClick={() => setCart([])}>
            Clear cart
          </button>
        </>
      );
    };
    
    export default Menu;
    

    【讨论】:

    • 哦,我明白了。谢谢。所以我不需要另一个钩子来做柜台
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多