首页 > 解决方案 > 从 vuex 存储中排序数组(无限渲染警告)

问题描述

我正在从 vuex 存储中检索一组对象,并尝试在我的一个组件中对该数组进行排序(我不想在存储中对数组进行排序)。但是我的浏览器出现错误infinite update loop in a component render function。这里发生了什么,我该如何解决这个问题?

<template>
  <div
    v-for="(item, i) in itemList">
    {{item.description}}
  </div>
</template>


computed: Object.assign({},
  mapGetters({
    currentItemList: "item/current",
  }),
  {
   itemList() {
     if(this.currentItemList != undefined) {
       return this.currentItemList.sort(function(a, b) {
           var textA = a.description.toUpperCase()
           var textB = b.description.toUpperCase()
           return (textA < textB) ? -1 : (textA > textB) ? 1 : 0
         })
      }
      else {
        return []
      }
    },
  }
)

标签: vue.js

解决方案


随着this.currentItemList.sort您在计算属性中改变反应性数据 - 这将触发组件始终重新渲染......不要改变计算属性中的数据。相反,请确保对数组的副本进行排序:this.currentItemList.slice().sort(...)


推荐阅读