【问题标题】:Getting Firebase doc.data is undefined获取 Firebase doc.data 未定义
【发布时间】:2020-03-26 11:55:15
【问题描述】:

我正在尝试从我的 firebase 集合中获取数据。当我安慰。 doc.data().name 它正在返回名称,但是当我尝试将 doc.data().name 分配给变量时,它向我显示未定义的错误。我正在使用 Vuex 和 firebase。

created() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log(user.uid);
        firebase.firestore().collection("profiles").doc(user.uid)
          .get()
          .then(function(doc) {
            console.log("Document data:", doc.data().name);  // Getting value from firebase
            this.profile.name = doc.data().name;   // Getting Undefined Here
          })
          .catch(function(error) {
            console.log("Error getting document:", error);
          });
      } else {

      }
    });
  }


data() {
    return {
        profile: {
            name: null
        }
    };
  },

【问题讨论】:

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


    【解决方案1】:

    改变这个:

              .then(function(doc) {
                console.log("Document data:", doc.data().name);  // Getting value from firebase
                this.profile.name = doc.data().name;   // Getting Undefined Here
              })
    

    进入这个:

              .then((doc) => {
                console.log("Document data:", doc.data().name);  // Getting value from firebase
                this.profile.name = doc.data().name;   // Getting Undefined Here
              })
    

    使用箭头函数,来自文档:

    箭头函数没有自己的 this。使用封闭词法范围的 this 值;箭头函数遵循正常的变量查找规则。因此,在搜索当前范围内不存在的 this 时,箭头函数最终会从其封闭范围中找到 this

    【讨论】:

    • 感谢您的回答。我仍然出现这个错误----文档数据:Rahul Kundu dashboardTopbar.vue?5982:99 获取文档时出错:TypeError:无法设置未定义的属性“名称”
    • 尝试将 auth 回调更改为箭头函数,它应该修复 this 关键字的范围。所以把firebase.auth().onAuthStateChanged(function(user) {改成firebase.auth().onAuthStateChanged((user) => {
    • 是的。谢谢你成功了。基本上我必须将所有功能更改为箭头功能。
    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2023-03-08
    • 2017-01-02
    • 2016-10-20
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多