【发布时间】:2022-01-14 18:13:44
【问题描述】:
基本上,我在我的 Next.js 应用程序(即profile 和dashboard)中为两个页面创建了一个 HOC,如果用户未经授权,两个页面将阻止他们访问它们。
示例:pages/profile.js
import withAuth from "../components/AuthCheck/index";
function Profile() {
return (
<>
<h1>Profile</h1>
</>
)
}
export default withAuth(Profile);
我的身份验证组件/HOC:
import { useRouter } from 'next/router'
import { useUser } from '../../lib/hooks'
import { PageLoader } from '../Loader/index'
const withAuth = Component => {
const Auth = (props) => {
const { isError } = useUser(); //My hook which is calling /api/user see if there is a user
const router = useRouter()
if (isError === 'Unauthorized') {
if (typeof window !== 'undefined' && router.pathname === '/profile' || router.pathname === 'dashboard') router.push('/login')
return <PageLoader />
}
return (
<Component {...props} />
);
};
if (Component.getInitialProps) {
Auth.getInitialProps = Component.getInitialProps;
}
return Auth;
};
export default withAuth;
现在发生的情况是,如果您碰巧在浏览器 URL 栏中输入 /profile 或 /dashboard,在重定向之前您会看到页面一秒钟,即闪烁。
知道为什么会这样吗?
【问题讨论】:
-
因为重定向发生在客户端 - 在它发生之前,您将首先在服务器上看到生成的页面。防止它的唯一方法是在服务器端重定向。
-
@juliomalves 很有趣。谢谢。那么你会把这个逻辑放在哪里呢?
标签: reactjs next.js higher-order-components next-router