【发布时间】:2021-11-23 09:48:40
【问题描述】:
我建立了一个简单的项目,通过使用 if 和 else 语句保护网站的路由/页面,并为每个页面添加一个函数 withAuth(),但我不确定这是否是最好的方法用 nextjs 保护路由,我注意到保护路由或页面有延迟,比如 2-3 秒长,他们可以在将访问者或未注册用户重定向到登录页面之前看到页面的内容.
有没有办法摆脱它或使请求更快,以便未注册的用户不会查看页面的内容? nextjs框架中是否有更好的方法来保护某条路由?
代码
import { useContext, useEffect } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";
const withAuth = (Component) => {
const Auth = (props) => {
const { user } = useContext(AuthContext);
useEffect(() => {
if (!user) Router.push("/login");
});
return <Component {...props} />;
};
return Auth;
};
export default withAuth;
withAuth 使用示例
import React from "react";
import withAuth from "./withAuth";
function sample() {
return <div>This is a protected page</div>;
}
export default withAuth(sample);
【问题讨论】:
标签: javascript reactjs security next.js