[英]My else part of add to cart functionality is also putting the new quantity in the cartItems array rather than just increasing quantity of Items
cartItems 是一個 state 數組,其中包含用戶添加的項目,我使用的邏輯是,如果該項目已經存在於購物車中,則增加其數量,否則將數量設為 1。
const [cartItems,setCartItems]=useState([])
const handleAddItem=(item)=>{
if(!cartItems.find(product=>product.id===item.id)){
setCartItems([...cartItems,{...item,quantity:1}])
}
else{
setCartItems([...cartItems,
cartItems[cartItems.findIndex(product=>product.id===item.id)]
.quantity++])
}
}
將項目添加到購物車 5 次后,我得到以下結果,但我只想要數組中的 object 而不是其他元素。
[Object, 1, 2, 3, 4]
0: Object
id: 1
name: "Sunday"
price: 100
quantity: 5
1: 1
2: 2
3: 3
4: 4
弄清楚下面的代碼可以在其他條件下使用
else{
cartItems[cartItems.findIndex(product=>product.id===item.id)].quantity++
setCartItems([...cartItems])
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.