【问题标题】:Stucked in infinite loop (Vue.js)陷入无限循环(Vue.js)
【发布时间】:2020-05-16 02:42:43
【问题描述】:

我在 firebase、帖子和用户中有 2 个文档,在帖子表中我有一个 uid,我在帖子文档中的 uid 的帮助下从用户文档中获取“头像”字段,请参阅代码:

     fetchAvatar(uid){
     var avatar;
     this.$db.collection("users")
         .doc(uid)
         .get().then(snapshot => {
         avatar = snapshot.data().avatar
     });
     return avatar;
 }

 <q-list
   class="rounded-borders q-mt-md q-mb-md"
   v-for="(post, key) in posts"
   :key="post.key"
  >
   <div v-if="key == 0" v-scroll-fire="(new_group = false)"></div>
   <PostDisplay
    :key="key"
    :type="post.type"
    :avatar="fetchAvatar(post.uid)" // Calling function there
    :more="post.more"
    :name="post.owner"
    :group="post.group_name"
    :timestamp="post.created_at"
    :likeCount="post.likes.length"
    :commentCount="post.comments.length"
    :comments="post.comments"
    :text="post.text"
    doc="posts"
    :id="post.id"
    class="dropshadow"
    :media-urls="post.mediaUrls"
    :post="post"
   />
  </q-list>

Infinite loop error

我需要一个适当的解决方案来解决这个错误,我非常感谢给我正确答案的人。

【问题讨论】:

  • 当您在循环中有相同的键时会出现此错误。所以为此只需在循环内使用不同的键
  • 我将 post.key 编辑为 post.uid 但这不是关键问题,我搜索并阅读了许多博客/网络/帖子,如果循环中的数据发生更改,Vue.js 会重新渲染循环,所以我正在寻找一种通过 post.uid 为每个帖子获取头像的方法,你有什么解决方案吗?

标签: javascript vuejs2 infinite-loop


【解决方案1】:

key="post.key" 看起来很可疑。我怀疑这些帖子有一个关键属性。你真的应该使用post.id 作为键。 在PostDisplay 上定义key 是没有用的,因为您已经在父级上定义了一个。 此外,(post, index) 而不是 (post, key) 将有助于避免混淆概念。

旁注:

  • 将单个属性(类型、更多、所有者、...)传递给 PostDisplay 是可以的。通过整个post 也可以。但同时做这两件事很奇怪。
  • 更多问题,我看到你在每个 PostDisplay 上传递整个 posts 数组。您真的应该让 PostDisplay 发出事件并让其父级作用于帖子数组。

编辑: 无论如何,要找出问题所在,您可以删除代码的某些部分,直到它再次开始运行。尝试使用 v-scroll-fire 删除 div。然后尝试移除头像属性。

据说你的 fetchAvatar 是错误的。它将始终返回 undefined 因为 $db 调用是异步的,avatar = ... 将始终在函数 fetchAvatar 返回它的(未定义)值之后进行评估。 我可能会做什么:

// :avatar="fetchAvatar(post.uid)"
fetchAvatar(uid) {
  return () => this.$db.collection("users")
         .doc(uid)
         .get().then(snapshot => snapshot.data().avatar)
}

在 PostDisplay.vue 上:

data() { return { fetchedAvatar: '' } },
created() { // or mounted()
  this.avatar().then(avatar => { this.fetchedAvatar = avatar })
}

【讨论】:

  • 我将 post.key 编辑为 post.uid 但这不是关键问题,我搜索并阅读了许多博客/网络/帖子,如果循环中的数据发生更改,Vue.js 会重新渲染循环,所以我正在寻找一种通过 post.uid 为每个帖子获取头像的方法,你有什么解决方案吗?
  • 使用 post.uid 作为键并不是更好,因为我猜同一个用户可以发布多个帖子。如果您在帖子上没有唯一 ID,:key="key" 仍然是最安全的。我编辑了关于其他可能问题的答案。
  • 你的解决方案不起作用,亲爱的你不明白这个问题,问题是正如我所说,当我在 v-for 循环中使用 post.uid 获取数据时 vue 看到任何变化v-for 循环它重新渲染循环周期,因此它正在创建无限循环。
  • 说真的,您甚至没有就我提供的解决方案提供反馈(fetchAvatar 替代方案并让 PostDisplay 从挂钩开始提取)。你希望我们如何进步?
  • 我告诉过你,你的解决方案不起作用,我想使用 post.uid 在循环中获取头像。
猜你喜欢
  • 2020-05-13
  • 1970-01-01
  • 2013-03-17
  • 2021-02-15
  • 2022-01-23
  • 2021-01-23
相关资源
最近更新 更多