React更新项目数量在购物车中
我正在尝试更新每个项目的数量,我尝试了我的代码,但是它无法正常工作,但是当我尝试在此处找到解决方案时:使用React Redux在购物车中更新商品数量,它效果很幸运。 但是我想了解为什么我的代码不起作用(我使用的不是usecontext不是redux,但通常与问题无关) **有效的代码:**:
cartItems: state.cartItems.map(item => item.id === payload.id
? {
...item,
qty: item.qty + 1,
}
: item
),
**我的不正常代码:**
if (productsInCard.find((x) => x.name === e.name)) {
let qu ; //to get the new quantity
const arr = [...productsInCard];
productsInCard.forEach((ele, index) => {
if (ele.name === e.name) {
qu = ele.quantity + 1;
console.log(ele.quantity + " this is the quantity before +1")
arr.splice(index, 1);
addCard(arr);
console.log("old item deleted" + JSON.stringify(arr))
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
console.log(" item + quantity added : " + JSON.stringify(productsInCard));
}
});
const newArr = [...productsInCard]
productsInCard.forEach((ele, index)=>{
if(ele.name === e.name){
console.log(ele.quantity)
if (ele.quantity < qu)
newArr.splice(index, 1)
addCard(newArr);
}
})
} else {
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: 1,
},
]);
console.log("list with new item : " + productsInCard);
}
}
I'm trying to update the quantity of each item , i have tried my code but it didn't work correctly, but when i tried a solution found here: How to update item quantity in the shopping cart using React Redux , it worked thankfully .
But i want to understand why my code didn't work (i'm using useContext not redux but normally that has nothing to do with the problem )
**Code that worked : ** :
cartItems: state.cartItems.map(item => item.id === payload.id
? {
...item,
qty: item.qty + 1,
}
: item
),
**My unfunctional code : **
if (productsInCard.find((x) => x.name === e.name)) {
let qu ; //to get the new quantity
const arr = [...productsInCard];
productsInCard.forEach((ele, index) => {
if (ele.name === e.name) {
qu = ele.quantity + 1;
console.log(ele.quantity + " this is the quantity before +1")
arr.splice(index, 1);
addCard(arr);
console.log("old item deleted" + JSON.stringify(arr))
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
console.log(" item + quantity added : " + JSON.stringify(productsInCard));
}
});
const newArr = [...productsInCard]
productsInCard.forEach((ele, index)=>{
if(ele.name === e.name){
console.log(ele.quantity)
if (ele.quantity < qu)
newArr.splice(index, 1)
addCard(newArr);
}
})
} else {
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: 1,
},
]);
console.log("list with new item : " + productsInCard);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论