【问题标题】:Firebase and Vue Js lifecycle hooksFirebase 和 Vue Js 生命周期钩子
【发布时间】:2018-04-23 16:44:46
【问题描述】:

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

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

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

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"

我玩过所有的生命周期钩子:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    用户信息可能需要异步加载/刷新。因此,请始终使用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(),但它也应该适用于任何其他生命周期方法。

    【讨论】:

    • 嗨弗兰克!谢谢!我没有任何已安装的错误,但现在我得到:“未捕获(承诺)TypeError:无法设置未定义的属性'clientLocation'”。我控制台记录了该值及其正确性。有什么想法吗?
    • 嗯.... 粗箭头的使用应该确保this 保持不变。我更新了代码以明确捕获它。
    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 2021-03-26
    • 1970-01-01
    • 2017-12-06
    • 2020-01-15
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多