使用Vue组件渲染功能时无限循环 [英] Infinite loop when using Vue component render function

查看:116
本文介绍了使用Vue组件渲染功能时无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vue 组件来呈现一些表头,如下所示:

I'm using a Vue component to render some table header as follows:

render (createElement) {
  return createElement('div', { class: 'header' },
    Array.apply(null, { length: this.initHours.length }).map(() => {
      return createElement('div', { class: 'frame' }, this.getHourIndex() )
    })
  )
}

问题是当在hourIndex(通过数组运行)上完成console.log 时会无限循环.

Issue is that when console.log done on hourIndex (which runs through an array) is going infinite loop.

getHourIndex 函数是:

getHourIndex () {
  const headerData = this.initHours[this.hourIndex]
  this.hourIndex++
  console.log(this.hourIndex) /// this is what's telling me it's an infinite loop
  return headerData
}

关于为什么要执行此无限循环的任何方向(考虑到 hourIndex 数组只有 25 个元素)将不胜感激.

Any orientation about why is this doing this infinite loop (considering that hourIndex array has only 25 elements) will be appreciated.

推荐答案

每当组件呈现响应式数据时,如果数据发生变化,它也必须重新呈现该数据.这是反应性的一部分.所以渲染过程本身不应该改变数据,否则会出现无限循环:1)渲染,2)数据改变,3)导致重新渲染,4)数据改变,无限循环.

Whenever a component renders reactive data, it also has to re-render that data if it changes. That's part of reactivity. So the render process itself should never change data, or there will be an infinite loop: 1) render, 2) data changes, 3) causes re-render, 4) data changes, ad infinitum.

这就是这段代码中发生的事情,因为渲染函数增加了this.hourIndex:

That's what's happening in this code because the render function increments this.hourIndex:

this.hourIndex++

如果您只需要索引,请从 map 中获取:

If you just need the index, take it from the map:

Array.apply(null, { length: this.initHours.length }).map((_, index) => {
  return createElement('div', { class: 'frame' }, index )
})

这篇关于使用Vue组件渲染功能时无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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