【问题标题】:Infinite update loop无限更新循环
【发布时间】:2017-02-09 21:19:46
【问题描述】:

我正在尝试在 Vue.js 中构建一个可重用的 Image Loader 组件,它应该:

  1. 管理自己的缩略图数据
  2. 以父级的src为道具
  3. 根据道具显示不同的缩略图,使用相同的实例而不被破坏

所以它可能会从两个地方获取数据(自己的缩略图状态 || src 属性),我很难弄清楚如何管理它。也不太确定这是否是解决问题的正确方法。

此时我在控制台中收到无限更新循环警告。

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

这是我的代码。任何帮助将不胜感激。

<template>
  <div>
    <label class="fileContainer">
      <span class="icon is-large">
        <i class="fa fa-camera"></i>
      </span>
      <input type="file" :index="index" @change="updateThumbnail"/>
    </label>

    <object
      :data="pdfURL"
      type="application/pdf"
      :class="{visible: pdfURL != ''}">
    </object>

    <img :src="getSrc()" />
  </div>
</template>

<script>
export default {
  props: ["index", "srcProp"],
  data() {
    return {
      imageSrc: '',
      imageDataURI: '',
      pdfURL: '',
    }
  },
  methods: {
    getSrc() {
      if (typeof this.srcProp !== "undefined") {
        this.imageSrc = ''
        if (this.srcProp !== '') {
          this.imageSrc = this.srcProp
        } else {
          this.imageSrc = this.imageDataURI
        }
      } else {
        this.imageSrc = this.imageDataURI
      }
      return this.imageSrc
    },
    updateThumbnail(event) {
      this.$emit('change')
      const fileTypes = ['jpg', 'jpeg', 'png']
      const imgFile = event.target.files[0] || event.srcElement.files[0]
      const extension = imgFile.name.split('.').pop().toLowerCase()
      const isImg = fileTypes.indexOf(extension) > -1

      if (extension === 'pdf') {
        const pdfURL = URL.createObjectURL(imgFile);
        this.pdfURL = pdfURL
        this.height = 200
        return
      } else if (isImg) {
        var reader = new FileReader();
        reader.readAsDataURL(imgFile);
        reader.onload = () => {
          this.imageDataURI = reader.result
          return
        }
      } else {
        alert("Please submit images or PDFs only.")
      }
    },
  }
}
</script>

【问题讨论】:

  • 似乎getSrc 应该是一个计算的,其表达式是this.srcProp || this.imageDataURI
  • @RoyJ 谢谢。这似乎不起作用,因为这些图片上传者不止一个,下一个仍然有相同的this.imageDataURI
  • 你的代码能做到它应该做的吗?是您唯一发出警告,还是有其他问题?
  • 监听change事件的父组件是否改变了该组件的index属性?

标签: javascript vue.js


【解决方案1】:

我也遇到了同样的问题。让我向你解释一下我所知道的。

当使用:src="anyFunction()" 时,即使在得到结果后,它也会重新渲染到无限时间。

此时,我们可以无限次地获得相同的数组。尝试显示console.log('this.imgSrc'),你会得到无限个数组。

这里我们不能使用 slice 或 splice 来获取第一个数组。我还没有找到解决方案,但我设法将变量保留在 src 中,而不是渲染整个函数并获取 url。

<img :src="'https://maps.googleapis.com/maps/api/staticmap?zoom=15&size=500x250&markers=color:red%7Clabel:L%7C'+this.leadIpinfo.loc.split(',').slice(0,1)+','+this.Ipinfo.loc.split(',').slice(1,2) alt="loc">

在这里,我获取了数组并拆分并切片为 2 个值。

希望它能在某些方面有所帮助。

【讨论】:

  • 您很可能应该将其抽象为计算函数,因为动态参数中的许多逻辑看起来像代码异味
猜你喜欢
  • 1970-01-01
  • 2019-03-15
  • 2018-07-17
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多