Vue infinite update loop的问题解决

2022-01-11,,,,

这篇文章主要介绍了Vue "...infinite update loop..."的问题解决,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一个尤大大曾回复过的问题

vue warn : You may have an infinite update loop in a component render function

最近再写一个数组渲染时,源数据是拿到的数组经过排序后的数组,正常运行却出现爆红:

报红代码:

 computed: { ...mapState({ fromNames (state) { let fromNames = state.quote.fromNames; return fromNames.sort((a, b) => b.isBind - a.isBind);; }, }), },

然后...

然后百思不得解,最终找到源头:

你的确导致了一个无限循环, 因为array.sort()改变了数组自身,导致了过滤器又一次被触发。确保在副本上对数组排序:

 return value.slice().sort(...)

解决方案:

 computed: { ...mapState({ fromNames (state) { let fromNames = state.quote.fromNames; return fromNames.slice().sort((a, b) => b.isBind - a.isBind); }, }), },

数组方法 array.slice()用法

arr.slice([begin[, end]])

slice() 方法会浅复制(shallow copy)数组的一部分到一个新的数组,并返回这个新数组。

begin 起始位置 如果未定义,就默认0;如果大于数组长度,返回空数组;如果是负数,则从末尾算起;

end 结束位置(不包含该位置元素)如果省略了,就默认到末尾;如果大于数组长度,就取数组长度;如果是负数,则从末尾算起。

技巧:处理类数组对象

slice() 可以用于把一个类数组对象转化为一个新数组

例如:

 function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]

也可以使用.call绑定在函数的Function.prototype(也可以被简化为[].slice.call(arguments)

 var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { return slice(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]

或者

 [].slice.call({ 0: 0, 1 : 2, 2: 4, length: 4 }) //[0, 2, 4, empty]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

以上就是Vue infinite update loop的问题解决的详细内容,更多请关注本站其它相关文章!

《Vue infinite update loop的问题解决.doc》

下载本文的Word格式文档,以方便收藏与打印。