“在组件渲染函数中可能有无限的更新循环"Vue组件中的警告 [英] "You may have an infinite update loop in a component render function" warning in Vue component

查看:104
本文介绍了“在组件渲染函数中可能有无限的更新循环"Vue组件中的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建具有排序功能的基本表:

I'm creating a basic table with a sorting feature:

<template>
  <!-- more code -->
  <tr v-for="item in sortBy(data.body, { name: 'name', order: 1 })">
    <td v-for="field in item">{{ field }}</td>
  </tr>
  <!-- data.body => [{ name: Group 1 }, { name: Group2 }, // etc.] -->
</template>

props: {
  data: {
    type: Object,
    default () {
      return {}
    }
  }
},

methods: {
  sortBy (data, params) { 
    // the warning disappears if I only leave "return data"
    data.sort((a, b) => {
      return a[params.name] - b[params.name] * params.order
    })
    return data
  }
}

出于某种原因,我收到此警告:

For some reason, I'm getting this warning:

[Vue警告]:组件渲染函数中可能存在无限的更新循环.

[Vue warn]: You may have an infinite update loop in a component render function.

这是为什么以及如何解决?

Why is this is and how to fix it?

推荐答案

您收到警告,因为您正在更改sortBy中的data.body值.此数据更改将导致渲染功能再次运行.之所以没有出现无限循环,是因为在第二次调用sortBy时,数据已经被排序,因此数据不会更改为data.body.

You're getting the warning because you're changing the value of data.body within sortBy. This data change will cause the render function to run again. The reason you're not getting an infinite loop is that on the second call to sortBy the data is already sorted which results in no data change to data.body.

解决方案就是Jaromanda X提到的.使用slice将复制数组,这意味着data.body的值不会更改,因此不会调用任何重新渲染.

The solution is what Jaromanda X mentioned. Using slice will make a copy of the array which means data.body will not change in value, and therefore no re-render will be called.

return data.slice().sort(....

这篇关于“在组件渲染函数中可能有无限的更新循环"Vue组件中的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆