我面临购物车问题。无法增加购物车中现有项目的数量或添加其他项目。在按钮上,单击addToCart函数将执行以获取产品。
const [cartItems, setCartItems] = useState([])
const addToCart = product => {
console.log(product) // here I am getting the entire product
const index = cartItems.findIndex(item => item._id === product._id);
if (index === -1) {
const updateCart = cartItems.concat({
...product,
quantity: 1
});
setCartItems(updateCart);
} else {
const updateCart = [...cartItems];
updateCart[index].quantity += 1;
setCartItems(updateCart);
}
};
我只得到1种产品,如果我添加另一种产品或增加数量,它会被覆盖。
您的其他逻辑是错误的。您要在传播之前从carItems更新项目数量。更改:
const updateCart = [...cartItems];
updateCart[index].quantity += 1;
setCartItems(updateCart);
to
cartItems[index].quantity += 1;
const updateCart = [...cartItems];
setCartItems(updateCart);
编辑:请参阅下面的操作:
let cartItems = [{
_id: "1",
name: "shoe",
quantity: 1
}];
const addToCart = product => {
console.log(product) // here I am getting the entire product
const index = cartItems.findIndex(item => item._id === product._id);
if (index === -1) {
cartItems.push({
...product,
quantity: 1
});
const updateCart = [...cartItems];
console.log(updateCart);
} else {
cartItems[index].quantity += 1;
const updateCart = [...cartItems];
console.log(updateCart);
}
};
var product1 = {
_id: "1",
name: "shoe"
};
var product2 = {
_id: "2",
name: "apple"
};
addToCart(product1);
addToCart(product2);
let cartItems = [
{
_id: "1",
name: "shoe",
quantity: 1
}
];
console.log("START", JSON.stringify(cartItems), Array.isArray(cartItems));
const addToCart = product => {
console.log(product); // here I am getting the entire product
const index = cartItems.findIndex(item => item._id === product._id);
if (index === -1) {
const updateCart = cartItems.concat({
...product,
quantity: 1
});
cartItems = updateCart;
console.log("ADD", JSON.stringify(cartItems), Array.isArray(cartItems));
} else {
// original ... just works ...
// const updateCart = [...cartItems];
// updateCart[index].quantity += 1;
// ... this works, too
// cartItems[index].quantity += 1;
// const updateCart = [...cartItems];
// ... but this is safer (in react) as it replaces item with a new object
const updateCart = [...cartItems];
// new object for replace existing one
updateCart[index] = {
...updateCart[index],
quantity: updateCart[index].quantity + 1
};
cartItems = updateCart;
console.log("INC", JSON.stringify(cartItems), Array.isArray(cartItems));
}
};
var product1 = {
_id: "1",
name: "shoe"
};
var product2 = {
_id: "2",
name: "apple"
};
addToCart(product1);
addToCart(product2);
addToCart(product1);
console.log("END", JSON.stringify(cartItems), Array.isArray(cartItems));
使用新对象替换购物车中的项目[-行]可能是必须的。 f.e。:
cartItems.map( item => <CartOrderLine key={item._id} data={item} /> )
[<CartOrderLine />
具有相同的data
对象ref(仅更改为quantity
道具,没有替换)不会被渲染!