[英]Nuxt 3: Pinia: why is my mutating my state destorting the entire array
here lies my code这是我的代码
import { defineStore } from "pinia";
export const DB_CART = defineStore("CART", {
state: () => ({
CART: [
{
$id: "62616ffc6d13e2a9eb04",
quantity: 1
},
{
$id: "6261711719aa15827836",
quantity: 1
},
{
$id: "6275c020740fbd04db50",
quantity: 1
}
],
}),
actions: {
// INCREMENT PRODUCT QUANTITY IN CART
incrementCartQuantity(id) {
const cartItem = this.CART.find(item => item.$id = id);
cartItem.quantity++;
},
// DECREMENT PRODUCT QUANTITY IN CART
decrementCartQuantity(id) {
const cartItem = this.CART.find(item => item.$id = id);
if (cartItem.quantity === 1) return
cartItem.quantity--;
},
// ADD PRODUCT TO CART
addToCart(item) {
this.CART.push(item)
}
},
persist: true
})
I'd like to understand why when I increment or decrement a cart item starting from the second in the array, the array rearranges.我想了解为什么当我从数组中的第二个开始增加或减少购物车项目时,数组会重新排列。
incrementCartQuantity(id) {
const cartItem = this.CART.find(item => item.$id = id);
cartItem.quantity++;
console.log(this.CART) /*EXPECTED OUTPUT
[
{
$id: "62616ffc6d13e2a9eb04",
quantity: 1
},
{
$id: "6261711719aa15827836",
quantity: 1
},
{
$id: "6275c020740fbd04db50",
quantity: 1
}
]
*//*RETURED OUTPUT
[
{ $id: "6261711719aa15827836", quantity: 2 },
{ $id: "6261711719aa15827836", quantity: 1 }, INCREMENTED OBJECT
{ $id: "6275c020740fbd04db50", quantity: 1 }
]
*/
},
in my Vue component, on incrementCartItem, I find out that the entire array kind of shuffles and pops out the one at the top, and replaces it with the item which is being mutated I don't think the array should be affected in any way.在我的 Vue 组件中,在 incrementCartItem 上,我发现整个数组类型会随机播放并弹出顶部的那个,并将其替换为正在变异的项目我不认为数组应该受到任何影响.
Replace the item in the array with the updated one, using splice :使用splice将数组中的项目替换为更新的项目:
incrementCartQuantity(id) {
const index = this.CART.findIndex(i => i.$id === id);
if (index > -1) {
const item = { ...this.CART[index] };
item.quantity++;
this.CART.splice(index, 1, item)
}
}
Alternative syntax:替代语法:
incrementCartQuantity(id) {
const index = this.CART.findIndex(i => i.$id === id);
if (index > -1) {
this.CART.splice(index, 1, {
...this.CART[index],
quantity: this.CART[index].quantity + 1
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.