JavaScript中使用map函数修改购物车对象quantity时误替换整个对象的问题排查
Hey there! Let's break down why your current map function is replacing the entire object instead of just updating the quantity property, and how to fix it.
The Root Cause
Your current code does this:
state.cart.map(cartItem => cartItem.id === action.payload.id ? cartItem.quantity = action.payload.quantity : cartItem)
When you run cartItem.quantity = action.payload.quantity, that assignment operation returns the value you just set (in this case, 7), not the updated cartItem object. So for the matching item, you're replacing the entire object with just the number 7—that's why your cart array gets messed up.
The Correct Approach
To fix this, you need to return a new object for the matching item (to maintain immutability, which is crucial in state management like Redux) with the updated quantity, while keeping all other properties intact. Here's how:
state.cart.map(cartItem => { if (cartItem.id === action.payload.id) { // Return a new object with updated quantity, spread existing properties return { ...cartItem, quantity: action.payload.quantity }; } // Return the original item for non-matching entries return cartItem; });
Key Points:
- Immutability: Using the spread operator (
...cartItem) creates a copy of the original object, so we don't mutate the existing state directly. This is important for state consistency and change detection in frameworks like React. - Return the Object: Instead of returning the result of the assignment, we return the new object with the updated quantity, ensuring the array stays full of cart item objects.
If you prefer a concise one-liner version, you can write it like this (though the multi-line is more readable):
state.cart.map(cartItem => cartItem.id === action.payload.id ? { ...cartItem, quantity: action.payload.quantity } : cartItem );
That should resolve the issue—now only the quantity property of the matching cart item gets updated, and the rest of the object remains the same.
内容的提问来源于stack exchange,提问作者Umair Nadeem

