如何在React.JS中刷新后让用户登录firebase?

Joh*_*Cdf 7 authentication firebase reactjs 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/>
          );
    }
}

}
Run Code Online (Sandbox Code Playgroud)

这是我用来登录用户的方法(工作正常):

let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
Run Code Online (Sandbox Code Playgroud)

Rob*_*uch 15

我在 React 中使用 Firebase 时遇到了同样的问题。即使 Firebase 具有内部持久性机制,您在重新加载浏览器页面时也可能会遇到闪烁/故障,因为onAuthStateChanged接收经过身份验证的用户的侦听器需要几秒钟的时间。这就是我使用本地存储在 onAuthStateChanged 侦听器中设置/重置它的原因。类似于以下内容:

firebase.auth.onAuthStateChanged(authUser => {
  authUser
    ? localStorage.setItem('authUser', JSON.stringify(authUser))
    : localStorage.removeItem('authUser')
});
Run Code Online (Sandbox Code Playgroud)

然后可以在应用程序启动时在 React 组件的构造函数中检索它:

constructor(props) {
  super(props);

  this.state = {
    authUser: JSON.parse(localStorage.getItem('authUser')),
  };
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多关于它的信息

  • 将用户信息存储在localStorage中可以吗? (2认同)

Fra*_*len 12

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

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

constructor(props){
  super(props);
  firebase.auth().onAuthStateChanged(function(user) {
    this.setState({ user: user });
  });
}
Run Code Online (Sandbox Code Playgroud)