[英]How to add an item to the cart
我不太了解這個函數,比如“ cartItems.push(...product, count:1) ”實際上是做什么的? 我是初學者,我很難理解這些邏輯。 好心人幫我解釋一下! 非常感謝!
addToCart = (product) => {
let alreadyIncart = false;
const cartItems = this.state.cartItems.slice()
cartItems.forEach((item) => {
if(item.id===product.id){
item++;
alreadyIncart = true;
}
if(!alreadyIncart){
cartItems.push(...product, count:1)
}
})
}
這是一個細分,一步一步。
addToCart = (product) => {
// Sets boolean value if item is in cart initially to false, not found
let alreadyIncart = false;
// slice creates a shallow copy of the cartItems array
const cartItems = this.state.cartItems.slice();
// Iterate the cartItems copy, calling a function for each element
cartItems.forEach((item) => {
// if there is a matching item id
if (item.id === product.id) {
// increment item count
item++;
// set found to true
alreadyIncart = true;
}
// if item was not found in cart,
// add it to the cartItems array with an initial count value
if (!alreadyIncart) {
cartItems.push(...product, count:1)
}
})
}
但是,代碼似乎存在一些問題。
item
對象。 通常應該避免這樣的突變。 它也無效,因為item
是一個對象。 它應該在新的對象引用中更新count
屬性,即item.count++
,或者更確切地說, count: item.count + 1
。cartItems.push(...product, count:1)
在語法上是不正確的,它需要是單個對象,即cartItems.push({ ...product, count: 1 })
。更正確的版本將返回一個具有更新值的新數組,並且不會改變任何傳遞的參數。
addToCart = (product) => {
const { cartItems } = this.state;
// check if product is already in cart
const isInCart = cartItems.some(item => item.id === product.id);
if (isInCart) {
// if already in cart, return shallow copy array
// and shallow copy the matching item, then update
// the count by 1
return cartItems.map(item => item.id === product.id
? { ...item, count: item.count + 1 }
: item); // just return non-match
} else {
// Not in cart, just create item object with initial count 1
// concat appends to and returns a new array
return cartItems.concat({
...product,
count: 1,
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.