[英]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.