我正在尝试将商品添加到购物车而不进行 redux。我工作了,但我不认为我做得正确,因为我得到了一个奇怪的数量值。
到目前为止它是如何运作的。 您单击一个项目按钮,它会将 Prop 传递给handleAddCartItem()。 Prop 是addedItem(商品名称)和addedItemPrice。
默认状态
state = {
term: "",
cart: [
{
item: "",
price: 0,
quantity: 0
}
]};
处理程序如何工作。
handleAddCartItem = (addedItem, addedItemPrice) => {
// check if already in cart
let index = this.state.cart.findIndex(el => el.item === addedItem);
if (index == -1) {
console.log("item new to cart");
this.setState(prevState => ({
cart: [
...prevState.cart,
{
item: addedItem,
price: addedItemPrice,
quantity: 1
}
]
}));
} else {
this.setState(prevState => ({
quantity: (prevState.cart[index].quantity += 1)
}));
} };
我是新手,所以代码可能很抱歉。
我在处理程序中的逻辑 - 检查商品名称是否已在购物车数组内。
-如果是新添加的项目,则新对象将添加到数组中。
-如果项目已经在数组中,那么我使用当前在数组中的项目的索引,并且仅更新其数量。
我不明白为什么要添加额外的数量状态 =/
如有任何建议,谢谢。
最佳答案
我相信代码会说话,但如果您对某些事情感到困惑,请问我。
handleAddCartItem = (addedItem, addedItemPrice) => {
// check if already in cart
let index = this.state.cart.findIndex(el => el.item === addedItem);
if (index == -1) {
console.log("item new to cart");
this.setState(prevState => ({
cart: [
...prevState.cart,
{
item: addedItem,
price: addedItemPrice,
quantity: 1
}
]
}));
} else {
// THIS IS THE PROBLEM
this.setState(prevState => ({
quantity: (prevState.cart[index].quantity += 1)
}));
// HOW IT SHOULD BE
this.setState(prevState => {
let newCart = [...prevState.cart];
newCart[index].quantity += 1;
return {cart: newCart};
});
}
}
关于javascript - React 添加购物车重构 - 未知添加状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53538551/