我的状态看起来像这样:
items: [
{ id: 1, name: 'banana', price: 100, quantity: 1 },
{ id: 2, name: 'apple', price: 200, quantity: 1 },
{ id: 3, name: 'blueberry', price: 300, quantity: 1 }
]
cart: []
我有一个功能,可以将商品插入购物车:
addItem = item => {
const { cart, total, itemQuantity } = this.state
const { price, id } = item
const i = cart.indexOf(item)
if (!cart.some(x => x.id === id)) {
this.setState({
cart: [...cart, { ...item, quantity: itemQuantity }],
total: total + (price * itemQuantity)
})
}
}
在添加该项目之前,我会检查该项目是否存在,以避免重复。我想要发生的是,如果该商品已添加到购物车中,我想找到该对象并更改其数量值。
这可以做到吗?
最佳答案
我认为下面的解决方案适合您,而无需对您的设计进行太多更新。您实际上只需对要添加到购物车的商品数组调用 Array.prototype
方法 reduce
即可。确保将cart
的当前状态作为初始值传递给reduce
(将其作为第二个参数传递)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
通过一些简单的逻辑,您只需检查购物车中是否已存在该商品 id(这只是一个由商品 id 键入的对象文字)。如果没有,请添加该对象并将数量属性设置为 1 - 如果是,只需将数量属性增加 1。
希望下面的示例很清楚并且可以帮助您:
//an array of items we want to add to the cart
var items = [{
id: 1,
name: 'banana',
price: 100,
quantity: 1
},
{
id: 2,
name: 'apple',
price: 200,
quantity: 1
},
{
id: 3,
name: 'blueberry',
price: 300,
quantity: 1
}
];
//function utilizing reduce to update our cart object
function updateCart(cartToUpdate, itemsToAdd) {
itemsToAdd.reduce(function(cart, cartItem) {
if (!cart[cartItem.id]) {
cart[cartItem.id] = {
name: cartItem.name,
price: cartItem.price,
quantity: 1
}
} else {
cart[cartItem.id].quantity++;
}
return cart;
}, cart);
}
//implement cart as an object keyed on item id
var cart = {
1: {
name: 'banana',
price: 100,
quantity: 1
}
};
//i manually added a single banana to the cart so we can show that our update function works properly
console.log('Cart before update:');
console.log(cart);
updateCart(cart, items);
console.log('Cart after update:');
console.log(cart);
//from here it's really easy to see how many of each item we have in the cart:
Object.keys(cart).forEach(function(key) {
console.log(`The customer has ${cart[key].quantity} ${cart[key].name}(s) in their cart`)
});
//
关于javascript - 添加到数组后更改对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142385/