我所面临的问题是,当我将一个对象推到一个数组后,它将对更改作出反应。
// actions.js
export const addToCart = ({ commit }) => {
commit('addToCart'); // properly commits to change the state
setTimeout(function () {
commit('resetToppings');
}, 10000);
};
// mutations.js
export const addToCart = (state) => {
state.cart.push(state.orderItem);
};
export const resetToppings = (state) => {
state.orderItem.toppings = [];
};
// state.js
cart: [],
orderItem: {
quantity: 1,
toppings: [],
},orderItem被正确地推到cart上,但是10秒后,当我resetToppings时,它会重置cart内部和orderItem中的顶部。
如何确保resetToppings不会在cart中发生任何变化
发布于 2018-04-19 18:10:25
当您推送state.orderItem时,您可以在数组中添加对它的引用。因此,当state.orderItem更改时,数组中的元素会发生变化,因为它(数组中的元素)实际上仍然指向同一个(state.orderItem)对象。
您可以推送orderItem对象的浅层克隆:
// mutations.js
export const addToCart = (state) => {
state.cart.push({...state.orderItem});
};这样,添加到数组中的是一个不同的对象。
注:您可以:
state.cart.push({...state.orderItem});但是,只有在调用toppings之后,才能从/向addToCart数组中直接删除/添加元素。也就是说,如果在向resetToppings添加新元素之前调用toppings (因为resetToppings分配了一个新数组),这将有效。
如果情况并非总是如此,我的意思是,如果有时在调用toppings之后直接编辑addToCart数组,那么您也可以克隆它:
state.cart.push(Object.assign({...state.orderItem}, {toppings: [...state.orderItem.toppings]}});https://stackoverflow.com/questions/49927380
复制相似问题