【问题标题】:Vuex store, why adding to array overwrites all values in store with last entry?Vuex存储,为什么添加到数组会用最后一个条目覆盖存储中的所有值?
【发布时间】:2018-12-20 21:27:57
【问题描述】:

我正在使用 vuex 打字稿。这是一个商店模块:

import { getStoreAccessors } from "vuex-typescript";
import Vue from "vue";
import store from "../../store";
import { ActionContext } from "vuex";
class State {
  history: Array<object>;
}

const state: State = {
  history: [],
};

export const history_ = {
  namespaced: true,
  getters: {

    history: (state: State) => {

      return state.history;
    },

  },
  mutations: {

    addToHistory (state: State, someob: any) {

      state.history.push(someob);

    },

    resetState: (s: State) => {
      const initial = state;
      Object.keys(initial).forEach(key => { s[key] = initial[key]; });
    },
  },

  actions: {
    addToHistory(context: ActionContext<State, any>, someob: any) {
      commitAddToHistory(store, someob);
    }

  }

const { commit, read, dispatch } =
  getStoreAccessors<State, any>("history_");
const mutations = history_.mutations;
const getters = history_.getters;
const actions = history_.actions;

export const commitResetState = commit(mutations.resetState);
export const commitAddToHistory = commit(mutations.addToHistory);
export const getHistory = read(getters.history);
export const dispatchAddToSearchHistory = dispatch(actions.addToHistory);

现在如果调用dispatchAddToSearchHistorycommitAddToHistory,所有值都会被覆盖。例如,如果我添加一个元素来存储,那么它看起来像这样:

store = [
  {
    a: 1
  }
]

现在当我添加另一个对象时,{b: 2} store 变成了

store = [
  {
    b: 2
  },
  {
    b: 2
  }
]

所有值都被最后一个条目覆盖。例如,如果我尝试添加 {c:3} 然后商店看起来像(等等):

store = [
  {
    c: 3
  },
  {
    c: 3
  },
  {
    c: 3
  }
]

【问题讨论】:

  • 我看到的唯一奇怪的事情是您从history_ 对象中定义了state,并且看起来它从未作为history_ 的属性添加。在small example on the GitHub 中,state 被定义 basket 存储对象上。您可以尝试在 Object 上定义它,看看是否有任何改变?
  • 我从字面上复制粘贴该逻辑并且仍然得到相同的东西。好吧,这令人沮丧。

标签: javascript vue.js vuejs2 vuex vuex-modules


【解决方案1】:

....hmmmm,好吧,我想你可能每次都发送同一个对象

请尝试这个突变

addToHistory (state: State, someob: any) {
  state.history.push({...someob});
},

或者这个动作

addToHistory(context: ActionContext<State, any>, someob: any) {
  commitAddToHistory(store, {...someob});
}

this 使用扩展运算符克隆对象。这样,您添加的每个项目都将成为新对象。

【讨论】:

  • 这是有效的,你做了什么黑客攻击?这个 {...someob} 是什么意思?
  • 它被称为扩展运算符,它是一个es6特性;与Object.assign(...) 类似,它们创建对象的副本,这确保您添加了一个新对象,而不是同一对象的新实例
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多