问题描述
我有一个小问题,我正在学习 reactjs。我正在尝试向购物车数组中名为数量的对象添加一个属性;当具有相同id的相似项等于迭代器时,添加一个属性数量并增加它的值。我正在学习 react 和 javascript 我来自 python 背景所以...... 这是我的代码。
const addToCart = (item) => {
if (cart.length){
for (let iter of cart){
if (iter.id===item.id){
item.quantity += 1 // this is 'NaN' if quantity wasn't declared.
setCart([...cart,item])
}else{
setCart([...cart,item])
}
}
}
}
这段代码……什么都没有!
解决方法
如果我理解正确,如果该商品存在于购物车中,您想增加数量,否则将其添加到购物车?如果是这样,请尝试以下操作:
const [cart,setCart] = useState([]);
...
const addToCart = (item) => {
// declare the quantity property if it doesn't exist
item.quantity = item.quantity || 1;
// get the index from the cart
const i = cart.findIndex(obj => obj.id === item.id);
// if the item exists increment the quantity
if(i > -1) {
const newCart = [...cart];
newCart[i].quantity = item.quantity + 1;
setCart(newCart)
} else {
// the item doesn't exist so add it to the cart
setCart([...cart,item]);
}
}