【问题标题】:Data rendered on the screen but has error on the console (Firebase with Vue): Uncaught (in promise) TypeError: Cannot read property 'contents' of null数据在屏幕上呈现,但在控制台上有错误(Firebase with Vue):未捕获(承诺中)类型错误:无法读取 null 的属性“内容”
【发布时间】:2021-06-26 01:17:27
【问题描述】:

我正在尝试让 lesson.contents 在屏幕上呈现,但我在控制台上出现了一些错误。这是代码(我在 Vue 3 中使用 Firebase)

<template>
  <AddContent :lesson="lesson" />
  <div v-if="lesson.contents.length"> 
    <h2>{{ lesson.contents }}</h2>
  </div>
  
</template>
 
<script>
import ContentList from "@/components/ContentList.vue";
import AddContent from "@/components/AddContent.vue";
import getDocument from "@/composables/getDocument";
import { ref } from "vue";
 
export default {
  props: ["id"],
  components: { AddContent },
  setup(props) {
    const { document: lesson } = getDocument("lessons", props.id);
 
    return { lesson };
  },
};
</script>
 
<style>
</style>

然后我有这个错误:

我感到困惑的是,我仍然能够在屏幕上呈现 lesson.contents:

我已经尝试了几个小时来修复它,但我找不到原因。我真的很感谢你的帮助。谢谢!

我的getDocument.js 代码:

import { watchEffect, ref } from 'vue'
import { projectFirestore } from '../firebase/config'

const getDocument = (collection, id) => {

  let document = ref(null)
  let error = ref(null)

  // register the firestore collection reference
  let documentRef = projectFirestore.collection(collection).doc(id)

  const unsub = documentRef.onSnapshot(doc => {
    // need to make sure the doc exists & has data
    if(doc.data()) {
      document.value = {...doc.data(), id: doc.id}
      error.value = null
    }
    else {
      error.value = 'that document does not exist'
    }
  }, err => {
    console.log(err.message)
    error.value = 'problem fetching the document'
  })

  watchEffect((onInvalidate) => {
    onInvalidate(() => unsub())
  });

  return { error, document }

}

export default getDocument

【问题讨论】:

  • 看起来getDocument() 应该返回一个初始对象,其中contents 设置为一个空数组。现在,它最初似乎没有 contents 属性
  • 谢谢。你会建议我做什么来解决它?我使用 Vue 调试器检查了 props,它显示了 contents 属性的数据。你可以在这里查看截图:screencast.com/t/z7TQt1pM
  • 请在您的问题中包含getDocument 实现。
  • This post 可能有助于说明我所说的“初始数据”
  • 我刚刚为getDocument.js 添加了我的代码。你能帮忙看看菲尔我能做什么吗?谢谢!

标签: javascript firebase vue.js google-cloud-firestore vuejs3


【解决方案1】:

这一行...

let document = ref(null)

将document 初始化为null。只有在onSnapshot 回调被执行后,它才会接收到带有contents 属性的值。

为了防止您的应用程序抛出...

无法读取 null 的属性“内容”

你可以用更好的默认值初始化document

let document = ref({ contents: [] })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 2021-02-28
    • 2021-09-25
    • 2022-01-21
    • 2020-11-08
    • 2023-03-13
    • 2021-09-04
    • 2018-08-26
    相关资源
    最近更新 更多