gpt4 book ai didi

reactjs - 你如何处理 NextJS 应用程序中的公共(public)和私有(private)路由?

转载 作者:行者123 更新时间:2023-12-03 15:47:58 24 4
gpt4 key购买 nike

我正在开发一个我们有公共(public)和管理路由的应用程序,在我们过去的 CRA 应用程序中,我们使用了自定义路由元素,但我们在 nextjs 中没有细线......我们有很多公共(public)页面,我们有 20私有(private)页面/路线。
在 nextjs 中处理 protected 认证路由和公共(public)路由的最佳方法是什么?
非常感谢!
最好的

最佳答案

我个人一直在为此使用 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);
如果需要,您可以使用角色检查(如公共(public)、普通用户和管理员)扩展 withAuth HOC。

关于reactjs - 你如何处理 NextJS 应用程序中的公共(public)和私有(private)路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com