Vuex 状态下的重复数组项(使用 Socket.io)

Posted

技术标签:

【中文标题】Vuex 状态下的重复数组项(使用 Socket.io)【英文标题】:Duplicate array items in Vuex state (using Socket.io) 【发布时间】:2021-06-08 12:42:54 【问题描述】:

所以我在 Vue 中构建了这个应用程序并使用了 Vuex。我使用 Socket.Io 连接到 Node/Express 后端,以便能够在需要时立即将数据从服务器推送到客户端。

推送到客户端的数据以对象的形式存储在 VUEX 的数组中。推入数组的每个数据对象都附加了一个唯一的字符串。

此字符串用于比较已在 VUEX 中推入数组的对象。如果有重复,它们将不会被存储。如果不相等 = 它们被存储。

然后我使用...mapGetters 在 Vuex 中获取数组并循环遍历它。为每个对象呈现一个组件。

但是 - 有时同一个对象会被渲染两次,即使 VUEX 中的数组清楚地只显示一个副本。

这是 VUEX 商店中的代码:

export default new Vuex.Store(
  state: 
    insiderTrades: [],
  ,

  mutations: 
    ADD_INSIDER_TRADE(state, insiderObject) 
      if (state.insiderTrades.length === 0) 
        // push object into array
        state.insiderTrades.unshift(insiderObject);
       else 
        state.insiderTrades.forEach((trade) => 
          // check if the insider trade is in the store
          if (trade.isin === insiderObject.isin) 
            // return if it already exists
            return;
           else 
            // push object into array
            state.insiderTrades.unshift(insiderObject);
          
        );
      
    ,
  ,
  getters: 
    insiderTrades(state) 
      return state.insiderTrades;
    ,
  ,

这是 App.vue 中的一些代码

mounted() 
  // //establish connection to server
  this.$socket.on('connect', () => 
    this.connectedState = 'ansluten';
    this.connectedStateColor = 'green';
    console.log('Connected to server');
  );
  //if disconnected swap to "disconneted state"
  this.$socket.on('disconnect', () => 
    this.connectedState = 'ej ansluten';
    this.connectedStateColor = 'red';
    console.log('Disconnected to server');
  );
  // recieve an insider trade and add to store
  this.$socket.on('insiderTrade', (insiderObject) => 
    this.$store.commit('ADD_INSIDER_TRADE', insiderObject);
  );
,

【问题讨论】:

【参考方案1】:

您的forEach 迭代现有项目并为每个现有项目添加一次新项目。使用Array.find

ADD_INSIDER_TRADE(state, insiderObject) 
  const exists = state.insiderTrades.find(trade => trade.isin === insiderObject.isin);
  if (!exists) state.insiderTrades.unshift(insiderObject);
,

您不需要初始的length 检查

【讨论】:

以上是关于Vuex 状态下的重复数组项(使用 Socket.io)的主要内容,如果未能解决你的问题,请参考以下文章

在reactjs中删除重复项后如何从状态值和setstate创建数组

Vuex Getters 是不是返回对状态的引用(数组、对象等)?

Vuex 状态数组对象的计算属性

包括处于vuex状态的html标签[重复]

为啥 Vuex 状态将数组作为对象返回

Vuex store - 将状态中的项目推送到状态数组导致数组中的前一个项目更改为当前状态项目