[英]page permission check with react router v6
I'm using useRoutes of React Router v6 to render routes, and I want to check permissions every time user access the page.我正在使用 React Router v6 的 useRoutes 来呈现路由,并且我想在每次用户访问该页面时检查权限。
I found below example,but is there any other way to use a wrapper for each page?我在下面找到了示例,但是还有其他方法可以为每个页面使用包装器吗? like next middleware.就像下一个中间件。
https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx https://stackblitz.com/github/remix-run/react-router/tree/main/examples/auth?file=src/App.tsx
about useRoutes: https://reactrouter.com/docs/en/v6/examples/route-objects关于 useRoutes: https://reactrouter.com/docs/en/v6/examples/route-objects
this is my code.这是我的代码。 it works but the problem is that NavBar is also invisible when an unauthorized user approaches.它有效,但问题是当未经授权的用户接近时,NavBar 也是不可见的。
function App() {
...
const routes: RouteObject[] = [
{
path: "/",
element: <RequireAuth role={"role test"} component={<NavBar />}></RequireAuth>,
children: [
{ index: true, element: <Home /> },
{
path: "/pricing",
element: <Pricing />,
},
{
path: "/guide",
element: <Guide />,
},
{
path: "/consult",
element: <Consult />,
},
{ path: "*", element: <Error /> }
]
}
];
let element = useRoutes(routes);
return (
<Fragment>
<GlobalStyle />
<ThemeProvider theme={theme}>
{element}
</ThemeProvider>
</Fragment>
);
...the problem is that
NavBar
is also invisible when an unauthorized user approaches. ...问题是当未经授权的用户接近时,NavBar
也是不可见的。
Move the Navbar
component outside the routes
configuration so it is always rendered regardless of route or auth status.将Navbar
组件移到routes
配置之外,以便无论路由或身份验证状态如何,它始终呈现。
const routes: RouteObject[] = [
{
path: "/",
element: <RequireAuth role={"role test"} />,
children: [
{ index: true, element: <Home /> },
{
path: "/pricing",
element: <Pricing />,
},
{
path: "/guide",
element: <Guide />,
},
{
path: "/consult",
element: <Consult />,
},
{ path: "*", element: <Error /> }
]
}
];
function App() {
...
const element = useRoutes(routes);
return (
<Fragment>
<GlobalStyle />
<ThemeProvider theme={theme}>
<NavBar /> // <-- render NavBar outside routes
{element}
</ThemeProvider>
</Fragment>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.