Javascript 在firebase身份验证中将用户设置为null
我试图倾听文档中的更改,但我得到了这个错误Javascript 在firebase身份验证中将用户设置为null,javascript,google-cloud-firestore,firebase-authentication,Javascript,Google Cloud Firestore,Firebase Authentication,我试图倾听文档中的更改,但我得到了这个错误 Uncaught TypeError: Cannot read property 'uid' of null 这是我的javascript代码 var user = auth.currentUser; db.collection('user-intro').doc(user.uid).onSnapshot(function(doc){ console.log(doc.data()); }) 其中我错了auth.currentUser为空。
Uncaught TypeError: Cannot read property 'uid' of null
这是我的javascript代码
var user = auth.currentUser;
db.collection('user-intro').doc(user.uid).onSnapshot(function(doc){
console.log(doc.data());
})
其中我错了
auth.currentUser
为空。这意味着在您调用它时没有用户登录。在使用分配给它的user
变量之前,需要检查该情况。您的auth.currentUser
在用户登录之前获取用户
如果用户刚刚登录或刷新页面,通常会发生这种情况。虽然Firebase在重新加载页面时恢复身份验证状态,但这需要一些时间,因为它需要根据服务器检查凭据
为确保代码仅在还原身份验证状态后运行,您需要将其包装在onAuthStateChanged
处理程序中:
firebase.auth().onAuthStateChange(function(user) {
if (user) {
db.collection('user-intro').doc(user.uid).onSnapshot(function(doc){
console.log(doc.data());
})
}
})
这不是sdk在您访问currentUser时告诉您的。也许你应该使用一个监听器,这样你就知道SDK告诉你用户是已知的。在新页面加载时,它不会立即可用: