[英]Function undefined when assigned to variable
我正在使用 Firebase 作為后端在 React 中進行一些身份驗證。
我有一個功能來檢查用戶是否按我的預期工作:
checkIfUserExists(uid) {
ref.child('users').child(uid).once('value', function(snapshot) {
if (snapshot.exists()) {
console.log("User exists");
return true;
} else {
console.log("User does not exist");
return false;
}
});
}
當我調用它傳遞 uid 時,如果用戶存在與否,它將寫入控制台。
this.checkIfUserExists(userId);
我只想獲得用戶是否登錄的布爾表示,但嘗試執行此類操作將始終打印“無用戶”。
if (this.checkIfUserExists(userId)) {
console.log('The user does really exist');
} else {
console.log('No user');
}
如果我嘗試
console.log(this.checkIfUserExists(userId));
控制台輸出“未定義”。
我是否以錯誤的方式接近這個? 為什么是未定義的?
內部函數內部的 return 語句不會通過外部函數返回值。 而是嘗試發送這樣的功能
checkIfUserExists(uid, callback) {
ref.child('users').child(uid).once('value', function(snapshot) {
callback.call(null, snapshot.exists());
});
};
checkIfUserExists(uid, function(exists){
if(exists){
console.log("User exists");
}else{
console.log("User does not exist");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.