我要从特定用户加载数据并将该数据推送到特定的输入字段。 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"
我玩弄了所有生命周期的钩子:
但数据无法显示。因为firebaseApp似乎没有加载"但是我无法取得" displayName"属性值因此无法填充数据的路径。
我应该如何/何时加载此代码,但似乎运行得太早?
答案 0 :(得分:2)
可能需要异步加载/刷新用户信息。因此,请始终使用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()
中,但它也适用于任何其他生命周期方法。