简体   繁体   English

添加 function 以从购物车中删除产品将不允许我添加更多产品

[英]Adding the function to remove products from the cart won't allow me to add more products

I have this function to add products and with their colors, however, once I added the functionality to remove products with their colors as well, it does not allow me to add a product anymore.我有这个 function 来添加产品和他们的 colors,但是,一旦我添加了删除产品和他们的 colors 的功能,它就不允许我再添加产品了。

  1. Add products and along with the selected color添加产品以及所选颜色
  2. Clicking the "-" button will remove the selected color for that product alone.单击“-”按钮将单独删除该产品的选定颜色。 What happens here is that if I'll add this functionality.这里发生的是,如果我将添加此功能。 it does not allow me to add any products anymore.它不允许我再添加任何产品。 There's no error that shows in the console nor does the app crashes as well.控制台中没有显示错误,应用程序也没有崩溃。

How can I fix this?我怎样才能解决这个问题? Thank you谢谢

Codesandbox: https://codesandbox.io/s/add-to-cart-sampled-2-efqrhd?file=/src/App.js代码沙盒: https://codesandbox.io/s/add-to-cart-sampled-2-efqrhd?file=/src/App.js

Codes: App.js代码: App.js

export default function App() {
  const [cartItems, setCartItems] = useState([]);
  const [searchList, setSearchList] = useState([]);
  const [searchKey, setSearchKey] = useState("");

  useEffect(() => {
    let x = [...products];
    x = x.filter((y) => {
      return y.prodName
        .toLocaleLowerCase()
        .includes(searchKey.toLocaleLowerCase());
    });
    setSearchList(x);
  }, [searchKey]);

  const handleAdd = (id, name, price, size, cat, color) => {
    console.log("add", id, name, price, size, cat, color);
    const productExist = cartItems.find(
      (item) => item.id === id && item.color === color
    );

    if (productExist) {
      setCartItems(
        cartItems.map((item) =>
          item.id === id && item.color === color
            ? { ...productExist, quantity: productExist.quantity + 1 }
            : item
        )
      );
    } else {
      setCartItems([
        ...cartItems,
        { id, name, price, size, cat, color, quantity: 1 }
      ]);
    }
  };

  const handleRemove = (product) => {
    console.log(product, "remove");
    const ProductExist = cartItems.find(
      (item) => item.id === product.id && item.color === product.color
    );

    if (ProductExist.quantity === 1) {
      setCartItems(cartItems.filter((item) => item.id !== product.id));
    } else {
      setCartItems(
        cartItems.map((item) =>
          item.id === product.id && item.color === product.color
            ? { ...ProductExist, quantity: ProductExist.quantity - 1 }
            : item
        )
      );
    }
  };

  const handleCartClearance = () => {
    setCartItems([]);
  };

  console.log(cartItems);

  return (
    <div className="App">
      <div>
        <input
          placeholder="Search product..."
          value={searchKey}
          onChange={(e) => setSearchKey(e.target.value)}
        />
        {searchList.map((item, index) => (
          <ul key={item.id}>
            <li>
              <b>{item.prodName}</b>
            </li>
            <li>Category: {item.cat}</li>

            <li>Size: {item.size}</li>
            <li>Php {item.price}.00</li>
            {Object.entries(item.colorMap).map((color) => (
              <>
                {color[1] !== 0 ? (
                  <>
                    {color[0]}

                    <button
                      onClick={(e) =>
                        handleAdd(
                          item.id,
                          item.prodName,
                          item.price,
                          item.size,
                          item.cat,
                          color[0]
                        )
                      }
                    >
                      Add
                    </button>
                    {/* <button onClick={(e) => handleAdd(index)}>Add to Cart</button> */}
                  </>
                ) : (
                  <>2</>
                )}
                <br />
              </>
            ))}
          </ul>
        ))}
      </div>
      <Cart
        cartItems={cartItems}
        handleCartClearance={handleCartClearance}
        handleRemove={handleRemove}
        handleAdd={handleAdd}
      />
    </div>
  );
}

Cart.js购物车.js

const Cart = ({ cartItems, handleCartClearance, handleRemove, handleAdd }) => {
  console.log(cartItems, "items");

  const totalAmount = cartItems.reduce(
    (price, item) => price + item.quantity * item.price,
    0
  );

  return (
    <div>
      Cart page
      {cartItems.length >= 1 && (
        <button onClick={handleCartClearance}>Clear Orders</button>
      )}
      {cartItems.length === 0 && <div>No Items in the cart</div>}
      <div>
        {cartItems.map((item) => (
          <div key={item.id}>
            <li>{item.id}</li>
            <li>{item.name + " " + item.size + "" + item.cat}</li>
            <li>{item.color}</li>
            <li>{item.quantity}</li>

            <li>Total: {parseInt(item.quantity) * parseInt(item.price)}</li>
            <button
              onClick={(e) =>
                handleAdd(
                  item.id,
                  item.prodName,
                  item.price,
                  item.size,
                  item.cat,
                  item.color
                )
              }
            >
              +
            </button>
            <button onClick={handleRemove(item)}>- </button>
          </div>
        ))}

        <div>
          <b>Total Amount :{totalAmount}</b>
        </div>
      </div>
    </div>
  );
};

export default Cart;

I think you should go simple to complex.我想你应该 go 简单到复杂。 As long as I understand, you have (1) UserInput (ie searchKey)据我了解,你有(1)UserInput(即searchKey)
(2) List (ie SearchList) (2)列表(即SearchList)
(3) Cart (ie cartItems). (3) 购物车(即cartItems)。
You need 2 functions.你需要2个功能。
(1). (1). addToCart(item)添加到购物车(项目)
(2). (2). removeFromCart(item)从购物车中移除(项目)

function addToCart(item){
//check item already exists or not
//if exists, return
//if not addToCart
}
function removeFromCart(item){
//check item exists in cart
//if not, return
//if exists, removeFromCart
}

You have arrays of objects.您有 arrays 个对象。 It is easy to check item exists or not with filter().使用 filter() 很容易检查项目是否存在。

const List = [{id: 0, name: 'a'},{id: 1, name: 'b'},...];
function addToCart(item){
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
}
function removeFromCart(item){
//these codes not even necessary
//const alreadyExist = cartItems.filter(cartItem=> cartItem.id === item.id).length > 0;
//if (!alreadyExist) return;
setCartITems(cartItems.filter(cartItem=> cartItem.id !== item.id);
}

what I am saying is, build simple functions first, then go to complex.我的意思是,先构建简单的函数,然后再构建复杂的 go。 Then, you will know where the error occurs.然后,您就会知道错误发生在哪里。 There is a way to debug when error does not show on screen.当屏幕上没有显示错误时,有一种调试方法。 console.log() . console.log() It can show you the value of your variables during the function. for example,它可以显示您在 function 期间变量的值。例如,

function addToCart(item){
console.log('Before adding CartItems is ', cartItems);
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
console.log('CartItem already Exist?', alreadyExist);
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
console.log(item, ' new item was added to CartItems');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM