我正在使用来自 webpack 的模块联合,我的核心应用程序包含到应用程序其余部分的所有路由。工作正常的是在里面Switch
,我只是拥有每个AuthRoute
或Route
手动而不是使用map
. Suspense
正在包装 Switch,以便直接子级只是Route
. 我现在正在做一些拆分,但我无法让它工作。有任何想法吗?
我的路线是这样设置的(localRoutes 在底部):
const routes = [
...localRoutes,
// ...remoteRoutes
];
在我的内部,我BrowserRouter
根据用户是否有权使用该路线来映射路线。我怀疑问题出在这里,但不明白为什么Route
或AuthRoute
返回 aRoute
不起作用,因为它是Switch
.
<Switch>
{routes.map((route) => {
console.log(route)
route.auth ?
<AuthRoute
key={route.path}
path={route.path}
component={route.component}
exact={route.exact}
requiredRoles={route.requiredRoles}
/>
:
<Route
key={route.path}
path={route.path}
component={route.component}
exact={route.exact}
/>
})}
<Redirect to='/login' />
</Switch>
其中 authRoute:
const AuthRoute = ({ Component, path, exact, requiredRoles }) => {
const isLoggedIn = true // or false
const roles = ['admin', 'sth_else']
const userHasRequiredRole = intersection(requiredRoles, roles).length > 0
const message = userHasRequiredRole ? 'Please log in to view this page' : "You can't be here!"
return (
<Route
exact={exact}
path={path}
render={(props) =>
isLoggedIn && userHasRequiredRole
? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: userHasRequiredRole ?
'/login' :
'/modules',
state: {
message,
requestedPath: path
}
}}
/>
)
}
/>
);
};
export default AuthRoute;
和示例路线:
const AboutPage = lazy(() => import('core/AboutPage'))
const LoginPage = lazy(() => import('core/LoginPage'))
const MyModules = lazy(() => import('core/MyModules'))
const routes = [
{
auth: true,
path: "/modules",
component: MyModules,
exact: false,
requiredRoles: [
String(UserRoles.Administrator),
String(UserRoles.AnotherRole),
String(UserRoles.Another)
]
},
{
auth: false,
path: "/about",
component: AboutPage,
exact: false,
}
];