我有一系列产品,当我已经有 1 个具有相同 ID 的产品时,我想再添加一个,
所以,首先我在数组中查找是否有一个具有相同 ID 的产品
const { product } = action.payload;
const productInCartIndex = state.items.findIndex(item =>
item.product.id === product.id
);
所以,我检查它是否存在于我的状态,如果存在,我想在数量上再增加一个
if (productInCartIndex >= 0) {
return {
...state,
items: [
...state.items,
state.items[productInCartIndex].quantity += 1
]
}
}
但是,当动作被触发时,结果第一个结果是:
items: Array(1)
0: product: {id: 1, title: "Foo", price: 290.9}
quantity: 1
length: 1
但是当我第二次触发操作时,我不知道为什么当它落在那个 IF 中时,它会向产品添加一个数量,(但在数组中又添加了一个项目)然后我可以不解决它。
items: Array(2)
0: product: {id: 1, title: "Foo", price: 290.9} quantity: 2
1: 2
length: 2
依此类推:
items: Array(3)
0: product: {id: 1, title: "Foo", price: 290.9} quantity: 3
1: 2
2: 3
length: 3
答案 0 :(得分:0)
您应该使用 Array.prototype.map 来编辑 object in an array:
items: state.items.map((item) =>
item.product.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
)