代码之家  ›  专栏  ›  技术社区  ›  Chris

推送到阵列的项目似乎对旧对象有反应

  •  0
  • Chris  · 技术社区  · 6 年前

    我面临的问题是,将对象推送到阵列后,它将对更改作出反应。

    // 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 ,它会重置 运货马车 以及在 订单项目

    我怎样才能确保 重置浇头 内部不会发生任何变异 运货马车 ?

    1 回复  |  直到 6 年前
        1
  •  2
  •   acdcjunior Mukul Kumar    6 年前

    当你推的时候 state.orderItem 在数组中添加对它的引用。那么什么时候 状态订单项目 更改时,数组中的元素会更改,因为它(数组中的元素)实际上仍然指向相同的( 状态订单项目 )对象。

    您可以推送 orderItem 对象:

    // mutations.js
    export const addToCart = (state) => {
        state.cart.push({...state.orderItem});
    };
    

    这样,添加到数组的对象就不同了。


    注意:您可以执行以下操作:

    state.cart.push({...state.orderItem});
    

    但只有在从不从/向 toppings 直接阵列 之后 这个 addToCart 被调用。也就是说,如果你打电话 resetToppings 将新元素添加到之前 浇头 (这将起作用,因为 重置浇头 指定新数组)。

    如果情况并非总是如此,我的意思是,如果您有时编辑 浇头 直接阵列 之后 这个 添加到Cart 调用时,您可能还想克隆它:

    state.cart.push(Object.assign({...state.orderItem}, {toppings: [...state.orderItem.toppings]}});