安装组件时,我想渲染登录屏幕或应用程序,具体取决于用户是否登录。但是,每次刷新时,用户都会注销。我如何让他们保持登录状态?
应用程序组件:
firebase.initializeApp(config); //init the firebase app...
class App extends Component {//this component renders when the page loads
constructor(props){
super(props);
this.state = {user: firebase.auth().currentUser};//current user
}
render(){
if (this.state.user) {//if you are logged in
return (
<Application/>
);
} else {//if you are not logged in
return (
<Authentication/>
);
}
}
}
这是我用来登录用户的方法(效果很好):
let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
最佳答案
用户的 token 会自动保存到本地存储,并在页面加载时读取。这意味着当您重新加载页面时,应该自动再次对用户进行身份验证。
最可能的问题是您的代码未检测到此身份验证,因为您的 App
构造函数在 Firebase 重新加载并验证用户凭据之前运行。要解决此问题,您需要 listen for the (asynchronous) onAuthStateChanged()
event ,而不是同步获取值。
constructor(props){
super(props);
firebase.auth().onAuthStateChanged(function(user) {
this.setState({ user: user });
});
}
关于reactjs - 在 React.JS 中刷新后,如何让用户保持登录到 firebase 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855851/