在 React.JS 中刷新后,如何让用户保持登录 Firebase? [英] How do I keep a user logged into firebase after refresh in React.JS?

查看:40
本文介绍了在 React.JS 中刷新后,如何让用户保持登录 Firebase?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安装组件时,我想呈现登录屏幕或应用程序,具体取决于用户是否登录.但是,每次刷新时,用户都会注销.我如何让他们保持登录状态?

When mounting a component, I'd like to render either a log in screen or the app, depending on wether the user in logged in. However, each time I refresh, the user is logged out. How would I keep them logged in?

 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/>
          );
    }
}

}

这是我用来登录用户的方法(效果很好):

This is the method I'm using to log in the user (which works fine):

let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);

推荐答案

用户的令牌会自动持久化到本地存储,并在页面加载时读取.这意味着当您重新加载页面时,用户应该自动再次进行身份验证.

The user's token is automatically persisted to local storage, and is read when the page is loaded. This means that the user should automatically be authenticated again when you reload the page.

最可能的问题是您的代码未检测到此身份验证,因为您的 App 构造函数在 Firebase 重新加载并验证用户凭据之前运行.要解决此问题,您需要监听(异步)onAuthStateChanged() 事件,而不是同步获取值.

The most likely problem is that your code doesn't detect this authentication, since your App constructor runs before Firebase has reloaded and validated the user credentials. To fix this, you'll want to listen for the (asynchronous) onAuthStateChanged() event, instead of getting the value synchronously.

constructor(props){
  super(props);
  firebase.auth().onAuthStateChanged(function(user) {
    this.setState({ user: user });
  });
}

这篇关于在 React.JS 中刷新后,如何让用户保持登录 Firebase?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆