2

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

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 时,将进入无限循环。

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 个元素)都将不胜感激。

4

1 回答 1

3

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.

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

this.hourIndex++

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 )
})
于 2021-03-03T01:29:17.097 回答