I am using React 16 to build a simple e-commerce app. When I delete items from the shopping cart, the order of the items displayed changes even though the original array is not mutated. And the new array is also correctly ordered. Neither are the keys in conflict. They also do not change during the course of the render process.
Here is the cart before removing one quantity from the first item:
Here is the cart after removing one quantity from the first item:
As you can see, the item jumps down to the last order.
Here is the removeFromCart
code:
export const removeFromCart = item => prevState => {
let index = prevState.cart.indexOf(item.key)
console.log('cart before removal', prevState.cart)
let newCart = [
...prevState.cart.slice(0, index),
...prevState.cart.slice(index + 1)
]
console.log('cart after removal', newCart)
return {
cart: newCart
}
}
Here is my CartPage
component:
function CartPage({ items, onAddOne, onRemoveOne }) {
return items.length > 0 ? (
<ul className="CartPage-items">
{items.map(item => (
<li key={item.key} className="CartPage-item">
<Item item={item}>
<div className="CartItem-controls">
<button
onClick={() => onRemoveOne(item)}
className="CartItem-removeOne"
>
–
</button>
<span className="CartItem-count">{item.count}</span>
<button
onClick={() => onAddOne(item)}
className="CartItem-addOne"
>
+
</button>
</div>
</Item>
</li>
))}
</ul>
) : (
<p>Your shopping cart is empty</p>
)
}
The full code can be viewed here The live app can be seen here
Open the console to see the array order. Please add a bunch of items to the cart and try removing one quantity at the time to see the problem reproduced.