我正在开发一个具有公共和管理路由的应用程序,在过去的 CRA 应用程序中,我们使用了自定义路由元素,但我们在 nextjs 中没有 Thins...我们有很多公共页面,我们有 20 个私人页面/路线。
在 nextjs 中处理受保护的经过身份验证的路由和公共路由的最佳方法是什么?
非常感谢!
最好的
我个人一直在为此使用 HOC(高阶组件)。
下面是一个身份验证 HOC 示例:
const withAuth = Component => {
const Auth = (props) => {
// Login data added to props via redux-store (or use react context for example)
const { isLoggedIn } = props;
// If user is not logged in, return login component
if (!isLoggedIn) {
return (
<Login />
);
}
// If user is logged in, return original component
return (
<Component {...props} />
);
};
// Copy getInitial props so it will run as well
if (Component.getInitialProps) {
Auth.getInitialProps = Component.getInitialProps;
}
return Auth;
};
export default withAuth;
您可以将此 HOC 用于任何页面组件。
这是一个用法示例:
const MyPage = () => (
<> My private page</>
);
export default withAuth(MyPage);
如果需要,您可以使用公共、普通用户和管理员等角色检查来扩展 withAuth HOC。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)