i have a array of products, and i want add one more quantity when i already have 1 product with same ID,
So, first i find in the array if haves one product with the same ID
const { product } = action.payload;
const productInCartIndex = state.items.findIndex(item =>
item.product.id === product.id
);
So, I check if it exists in my state, if it exists, I want to increase one more in the quantity
if (productInCartIndex >= 0) {
return {
...state,
items: [
...state.items,
state.items[productInCartIndex].quantity += 1
]
}
}
But, when the action is fired, the results first result is:
items: Array(1)
0: product: {id: 1, title: "Foo", price: 290.9}
quantity: 1
length: 1
But when I fire the action for the 2nd time, I don't know why when it falls there in that IF, it adds a quantity to the product, (but adds one more item in the array) and then I can't solve it.
items: Array(2)
0: product: {id: 1, title: "Foo", price: 290.9} quantity: 2
1: 2
length: 2
And so on:
items: Array(3)
0: product: {id: 1, title: "Foo", price: 290.9} quantity: 3
1: 2
2: 3
length: 3
question from:
https://stackoverflow.com/questions/65940839/how-i-can-change-this-array-with-immutabily-in-reducer 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…