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

How do I keep a user logged into firebase after refresh in React.JS?

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

应用组件:

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

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

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

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

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

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

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

constructor(props) {
  super(props);

  this.state = {
    authUser: JSON.parse(localStorage.getItem('authUser')),
  };
}

您可以在 here 上阅读更多相关信息。

个人感觉这种方式最好最简单

  state = {authUser: null,show:'none'};
 
     componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
       if (user) { this.setState({ authUser: true,show:'block'})} 
       else { this.setState({ authUser: false,show:'none'})}
    })
  }
  return{ /*important*/ this.state.authuser==false?
     <Login/>
     :this.state.authuser==true?
        <Home style={{display:this.state.show}}/>
        :<div>/*show loading/spash page*/
        </div>
   }

您还可以将路由添加到此,并将主页作为默认路由('/' 不要使用确切路径,而是使用路径),然后使其自动重新路由到登录或注册,如果用户未登录。