我正在将Firebase的Google身份验证集成到我的React应用程序中,并且遇到用户成功登录的问题,但是当页面刷新时,他不再登录。
我有一个文件Firebase.js
,其中包含我的所有firebase功能:
if (!firebase.apps.length) {
fb = firebase.initializeApp(config);
} else {
fb = firebase.apps[0];
}
module.exports = {
app: fb,
db: fb.database(),
auth: fb.auth,
isUserSignedIn: () => {
var user = fb.auth.currentUser;
if (user) {
return true;
} else {
return false;
}
},
signIn: () => {
var provider = new firebase.auth.GoogleAuthProvider();
fb.auth().signInWithPopup(provider).then(function(result) {
console.log("Signed in using Google.");
}).catch(function(error) {
console.log("Error occured with sign in.");
location.reload();
});
},
}
我的应用成功加载了谷歌登录弹出窗口,我在控制台中收到了消息"Signed in using Google."
但是,在我检查用户是否已登录的React组件中,当页面刷新时,表示用户未登录:
import fb from '../../../Firebase';
if (typeof window !== 'undefined') {
const container = document.getElementById('navBar');
let isSignedIn = fb.isUserSignedIn();
console.log("Signed in: " + isSignedIn);
ReactDOM.render(<UserLink props={{signedIn: isSignedIn }} />, container);
}
我检查了firebase auth控制台并知道用户已经过身份验证的事实,但由于某种原因我的应用程序没有接受。
任何人都可以帮我看看我做错了什么吗?
答案 0 :(得分:0)
使用auth state change callback获取登录状态,而不是依赖于代码在页面加载时开始运行时立即可用。 An example is in the documentation
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// User is signed out.
// ...
}
});