我目前正在使用react,redux和firebase进行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函数的更新。
答案 0 :(得分:0)
使用onAuthStateChanged
的侦听器通常是在整页转换后恢复身份验证状态的正确方法。由于在这种过渡过程中会发生重新加载,因此身份验证状态可能会发生变化。使用onAuthStateChanged
侦听器可确保Firebase在验证用户的身份验证状态后调用您的代码。由于这可能需要调用服务器,因此确实需要一些时间,因此您需要显示“正在加载...”动画。
如果状态转换不需要重新加载,例如当您仅在同一页面中呈现新路由时,则可以合理确定身份验证状态在转换时不会更改。在这种情况下,您可以将当前用户从先前的组件传递到新的组件。泰勒(Tyler)对此有很好的文章:Pass props to a component rendered by React Router。
在后一种情况下,firebase.auth().currentUser
也应保留其状态,您可以安全地使用它。在加载新路由之后,您仍然可以使用onAuthStateChanged
来检测身份验证状态的变化。