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

查看:24
本文介绍了“您可能在组件渲染函数中有无限更新循环";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天全站免登陆