Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

redux - How i can change this array with immutabily in reducer?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use Array.prototype.map to edit an object in an array:

items: state.items.map((item) =>
    item.product.id === product.id
      ? { ...item, quantity: item.quantity + 1 }
      : item
  )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...