javascript - 基于多种因素删除特定产品
问题描述
我正在尝试删除用户单击的特定产品。
到目前为止,当您尝试从购物车中删除产品时,它会根据产品的 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);
};
谢谢!
解决方案
如果使用 React JS,那么已经问过这样的问题,技巧是传递索引,同时调用 removeItemHandler
e.currentTarget.getAttribute("itemid");
这段代码依赖于数据,今天你的逻辑依赖于size
and color
,明天它可能是别的东西
可扩展代码:您可以UUID (probably v4)
在将东西添加到购物车时分配,然后将其设置为属性(或使用上述方法传递回调),然后获取 id 并找到它。
let id = e.currentTarget.getAttribute("UUID");
一行可以是通用的。
示例代码
codeandbox.io/s/delete-items-from-cart-g9qm5?file=/src/App.js
推荐阅读
- javascript - Javascript - 一键下载多个链接
- c# - 如何将 asp.net core api 应用程序部署到 azure
- c# - 我将如何着手做类库并将其插入到我的主窗体中,最好是一个例子?
- laravel - Laravel 验证需要这个或那个
- python-3.x - 可以设置 verify=False 以连接到 Intranet 网站吗?
- ios - UICollectionView willDisplayCell 和 didEndDisplayingCell 顺序
- php - 如何使用来自不同文件夹的命名空间?
- reactjs - 自动完成材料 ui 明文
- r - Github Action 不是在 Push 上运行,而是按计划运行
- wmic - Wmic:这些是谁的温度?