在此代码中,而不是显示“产品已添加到购物车”。警报消息,如果购物车中已有商品,我想更新购物车数量,请帮帮我。
const addToCart = (id) => {
const check = cart.every((item) => {
return item.id !== id;
});
if (check) {
const cartData = products.filter((el) => {
return el.id === id;
});
setCart([...cart, ...cartData]);
} else {
alert('The product has been added to cart.');
}
我在这里对您的变量的外观进行一些假设,但是通常,这是您需要的:
const products = [{id: 1, name: 'Prod 1'}, {id: 2, name: 'Prod 2'}, {id: 3, name: 'Prod 3'}, {id: 4, name: 'Prod 4'}]
const cart = [{id: 1, name: 'Prod 1', quantity: 1}, {id: 4, name: 'Prod 4', quantity: 1}];
const addToCart = (id) => {
const check_index = cart.findIndex(item => item.id === id);
if (check_index !== -1) {
cart[check_index].quantity++;
console.log("Quantity updated:", cart);
} else {
cart.push({...products.find(p => p.id === id), quantity: 1})
console.log('The product has been added to cart:', cart);
}
}
addToCart(4)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句