有没有检查像onAuthStateChanged火力用户的状态更快的方法?

问题描述 投票:0回答:1

我曾目前正在使用的反应,终极版和火力点一个next.js项目。当用户进入需要授权我使用下面的代码来重定向他们,如果他们没有通过认证的页面。

import React from 'react';
import Router from 'next/router';

import { firebase } from '../../firebase';
import * as routes from '../../constants/routes';

const withAuthorization = (needsAuthorization) => (Component) => {
  class WithAuthorization extends React.Component {
    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        if (!authUser && needsAuthorization) {
          Router.push(routes.SIGN_IN)
        }
      });
    }

    render() {
      return (
        <Component { ...this.props } />
      );
    }
  }

  return WithAuthorization;
}

export default withAuthorization;

我使用以下repo作为我的基地项目。问题是应用程序似乎正常工作,但是当我尝试导航到一个页面,要求身份验证时,我没有验证。我不是重定向立即而是首先显示的页面将重新定向。由于HOC用途

firebase.auth.onAuthStateChanged()

这是异步的。有没有,如果用户登录检查更快的方法。

我迄今所考虑的

firebase.auth().currentUser

但我的内部状态,当用户在另一个页面注销依赖于onAuthStateChanged功能的更新。

reactjs firebase redux firebase-authentication next.js
1个回答
0
投票

使用监听器onAuthStateChanged通常是在一个完整的页面过渡到恢复认证状态的正确方法。既然有重载在这样的转变发生的事情,有机会的话,该认证状态已经改变。使用onAuthStateChanged听众确保火力地堡调用你的代码已经验证了用户的认证状态之后。因为这可能需要到服务器的调用,这样做的确需要一些时间,所以你想显示“加载...”动画。

如果状态转换不需要重新加载,当你刚刚呈现在同一页面一条新的路线一样,那么你可以相当肯定的是,认证状态不会在过渡改变。在这种情况下,你可以从以前的组件当前用户进入新的一个。泰勒对此有一个很好的文章:Pass props to a component rendered by React Router

在后一种情况下firebase.auth().currentUser也应保留其状态,你可以放心地使用它。然后,您还是会使用onAuthStateChanged新干线加载后检测认证状态的变化。

© www.soinside.com 2019 - 2024. All rights reserved.