首页 > 解决方案 > 基于多种因素删除特定产品

问题描述

我正在尝试删除用户单击的特定产品。

到目前为止,当您尝试从购物车中删除产品时,它会根据产品的 ID 进行删除。不过,我需要它来检查尺寸、颜色和 ID。如果用户只点击尺寸 M,我不希望它同时删除“产品 A,尺寸 M”和“产品 A,尺寸 L”。

例如: 在此处输入图像描述

如果我尝试删除“尺寸 M”,它应该only删除“尺寸 M”,而不是“尺寸 L”(因为它们都具有相同的 ID)。

这是我删除产品的代码:

const removeItemHandler = (e) => {
    let id = e.currentTarget.getAttribute("itemid");
    let size = e.currentTarget.getAttribute("size");
    let color = e.currentTarget.getAttribute("color");

    const clonedCartItems = JSON.parse(JSON.stringify(cartItems));

    // Here is where I am trying to filter out the product. So it will only take the one the user is 
    clicking on
    let newCart = clonedCartItems.filter(
      (elem) => elem.id !== id && elem.size !== size
    );

    setCartItems(newCart);
  };

谢谢!

标签: javascriptreactjs

解决方案


如果使用 React JS,那么已经问过这样的问题,技巧是传递索引,同时调用 removeItemHandler

从组件状态的数组中删除元素

e.currentTarget.getAttribute("itemid");这段代码依赖于数据,今天你的逻辑依赖于sizeand color,明天它可能是别的东西

可扩展代码:您可以UUID (probably v4)在将东西添加到购物车时分配,然后将其设置为属性(或使用上述方法传递回调),然后获取 id 并找到它。

let id = e.currentTarget.getAttribute("UUID");

一行可以是通用的。

示例代码

codeandbox.io/s/delete-items-from-cart-g9qm5?file=/src/App.js


推荐阅读