【发布时间】:2020-12-31 11:13:11
【问题描述】:
我对这些东西不熟悉,但我对学习它充满热情。因此,请随意链接文档,我很乐意查找它们。我在 Reactjs 中构建了一个购物车列表组件。我实现了 addToCart 和 removeFromCart 函数。问题在于 removeFromCart 函数。我有一个 json 文件,我可以从中获取我的类别和产品。我有 onClick 声明,可以更改组件的状态并呈现所需类别的新产品列表。我添加了一个从购物车中删除产品的按钮,但该按钮只会减少产品的数量。我想在产品数量降至零以下时移除产品。这是我的代码,希望对你有所帮助。
changeCategory = (category) => {
this.setState({ currentCategory: category.categoryName });
this.getProducts(category.id);
};
resetCategory = (category) => {
this.setState({currentCategory: "",});
this.getProducts()
};
getProducts = (categoryId) => {
let url = "http://localhost:3000/products";
if (categoryId) {
url += "?categoryId=" + categoryId;
}
fetch(url)
.then((response) => response.json())
.then((data) => this.setState({ products: data }));
};
addToCart = (product) => {
let newCart = this.state.cart;
var addedItem = newCart.find((c) => c.product.id === product.id);
if (addedItem) {
addedItem.quantity += 1;
} else {
newCart.push({ product: product, quantity: 1 });
}
this.setState({ cart: newCart });
alertify.success(product.productName + " added to the cart.,", 2);
};
这是组件的状态:
state = {
currentCategory: "",
products: [],
cart: [],
};
最后是有问题的部分:
removeFromCart = (product) => {
let newCart = this.state.cart;
var addedItem = newCart.find((c) => c.product.id === product.id);
if (addedItem) {
addedItem.quantity -= 1;
}
// var zeroItem = addedItem.quantity ;
// zeroItem = newCart.filter((a) => a.addedItem.quantity !== 0)
// this.state.zeroItem.filter((c) => c.product.id !== product.id);
this.setState({ cart: newCart });
alertify.error(product.productName + " removed from the cart.", 2);
};
评论部分是我尝试过的,但显然它们没有用。当产品数量降至零以下时,如何在此类项目中删除产品? 提前谢谢大家。
对于那些愿意提供帮助的人:减少数量我没有问题。当addedItem 的数量低于0 时,我只需要一种方法来删除该特定对象。
【问题讨论】:
标签: javascript arrays reactjs