📅  最后修改于: 2022-03-11 15:00:41.441000             🧑  作者: Mango
const handleAddToCart = (clickedItem: CartItemType) => {
setCartItems(prev => {
// 1. Is the item already added in the cart?
const isItemInCart = prev.find(item => item.id === clickedItem.id);
if (isItemInCart) {
return prev.map(item =>
item.id === clickedItem.id
? { ...item, amount: item.amount + 1 }
: item
);
}
// First time the item is added
return [...prev, { ...clickedItem, amount: 1 }];
});
};