javascript - Firebase 和 Vue Js 生命周期钩子(Hook)

标签 javascript firebase firebase-realtime-database vue.js vuejs2

我正在尝试从特定用户加载数据并将该数据推送到特定输入字段。 Firebase 中的路径位于:

var query = db.ref('Clients/'+ clientName +'/form/');

我在 mounted() 生命周期钩子(Hook)中 fecth 数据如下:

mounted(){

// Grab current user logged in from Firebase
var user = firebaseApp.auth().currentUser;

if ( user ){
 // Grab displayName to use in path to retrieve that client's data
 var clientName = firebaseApp.auth().currentUser.displayName;

 // The path to that specific's client data
 var query = db.ref('Clients/'+ clientName+'/form/');

   query.once('value')
     .then((snapshot) => {

        // Get the client's location from Firebase and assign to  clientLocation data in the DOM
        this.clientLocation = snapshot.child('clientLocation').val();

     });
   }

}

当我进行更改并保存我的代码而不重新加载时,数据会被正确推送。但是在重新加载时出现以下错误:

 Error in mounted hook: "TypeError: Cannot read property 'displayName' of null"

我尝试了所有的生命周期钩子(Hook):

  1. 创建前
  2. 创建
  3. 挂载前
  4. 安装
  5. 更新前
  6. 已更新
  7. 销毁前
  8. 销毁

但数据不显示。由于似乎 firebaseApp 尚未“加载”,因此我无法获取“displayName”属性值,因此无法填充数据路径。

我应该如何/何时加载这段有效但似乎运行得太早的代码?

最佳答案

用户信息可能需要异步加载/刷新。因此,始终使用 an auth state listener以确保您的代码在用户可用时运行。从链接文档修改:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // Grab displayName to use in path to retrieve that client's data
    var clientName = firebaseApp.auth().currentUser.displayName;

    // The path to that specific's client data
    var query = db.ref('Clients/'+ clientName+'/form/');

    var that = this;
    query.once('value').then((snapshot) => {
       // Get the client's location from Firebase and assign to  clientLocation data in the DOM
       that.clientLocation = snapshot.child('clientLocation').val();
    });
  }
});

您可以将它放在 mounted() 中,但它也应该适用于任何其他生命周期方法。

关于javascript - Firebase 和 Vue Js 生命周期钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223035/

相关文章:

java - 我可以在 firestore 查询中设置多个 .whereEqualTo 指向文档中的字段吗?

database - 在不需要站点登录时让数据库 (Cloud Firestore) 处于不安全状态是否可以接受?

javascript - 上传到同一路径时如何强制 firebase 存储返回新的签名 url?

ios - 如何正确检索 firebase 数据库?

javascript - 运行一堆Firebase查询时,Cloud Function for Firebase在60秒后超时

javascript - Davis.js 作为 AMD 模块?

javascript - 在 Angular SPA 中将 Controller 添加到 index.html

javascript - 如何在单击按钮时显示 jQuery DatePicker?

javascript - 根据php对ajax请求的响应制作动态html表

javascript - 为什么它在安装时写入 firebase 而不是在单击时写入 native react ?