从State group id创建数组



我正在构建一个购物车,我的购物车产品数组来自一个州。当我按下"添加到购物车"按钮时,会出现以下功能(信息是产品信息所在的位置):

const [cart, setCart] = useState([])
function addToCart() {
setCart( arr => [...arr, {
name: infos[id-2].fullName,
value: infos[id-2].value,
id: infos[id-2].id
}])}

它的工作很好,但我有重复的id在购物车数组。这对结帐页面等有影响。所以我需要从购物车中创建一个包含所有购物车项目的新数组,但不包括重复项目,如下所示:

const newCart = [{
id: cart.id
name: cart.name
quantity: '' >times the id occurs on the cart array
price: cart.value
totalPrice: cart.value * quantity
}]

我该怎么做?我使用上下文来管理所有的状态

为什么要把重复的id放在购物车中呢?您可以在购物车对象中再包含一个字段,然后只更新它。

const cart = [{ name: "A", value: 100, id: 1, quantity: 1 }];
function addToCart() {
const item = infos[id - 2];
setCart((arr) => {
const newCart = [...arr];
const existingItem = newCart.find((i) => i.id === item.id);
if (existingItem) {
existingItem.quantity++;
} else {
newCart.push({
name: item.fullName,
value: item.value,
id: item.id,
quantity: 1,
});
}
return newCart;
});
}

最新更新