reactjs - 在 React.JS 中刷新后,如何让用户保持登录到 firebase 的状态?

标签 reactjs firebase authentication firebase-authentication

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

应用程序组件:

 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/

相关文章:

javascript - 如果您要查找的元素不存在,如何不破坏 Cypress 测试

ios - 如何检查 Firebase 权限是否被拒绝?

node.js - 如果用户未经过身份验证,则显示公共(public)逻辑 React JS 和 Node API

php - 如何在 CMS PHP 中自动注销非事件用户

javascript - React - 更改列表中组件的顺序

javascript - 以 csv 文件作为数据库的 Reactjs 网页

reactjs - 是否可以将对象作为变量传递到 graphQL 突变中?

ios - iOS 上 Firebase 崩溃报告的不可读错误(符号文件)

Firebase 5 Angular 5 AngularFireList.snapshotChanges() 错误

ios - Facebook SDK 使用 Swift 3 iOS 10 登录