当所有路由根据条件动态加载时如何重定向到路由?
这是我根据上下文中的用户对象加载路由(反应路由器 dom 5)的代码。
function App() {
return (
<UserContextProvider>
<BrowserRouter>
<Navigation/>
</BrowserRouter>
</UserContextProvider>
);
}
导航代码。这里我有条件地加载路由。
function Navigation() {
const { contextState } = useUserContext();
const routes = contextState.user ? routesAuthenticated : routerUnauthenticated;
return (
<Switch>
{routes.map((route, index) => {
return (
<Route
key={index}
path={route.path}
exact={route.exact}
render={(props: RouteComponentProps) => (
<route.component name={route.name} {...props} {...route.props} />
)}
/>
);
})}
</Switch>
);
}
您会看到基于上下文用户对象我加载了不同的路由。路由是简单的配置文件:
export const routerUnauthenticated: IRoute[] = [
{
path: '/register',
name: 'Register page',
component: RegisterPage,
exact: false,
},
{
path: '/login',
name: 'Login page',
component: LoginPage,
exact: false,
}...
问题是我在路上http://localhost:3000/login,成功登录后我得到了带有 route 的空白页面http://localhost:3000/login。在登录之前,我有 3 条路线登录/注册/主页。登录后,我有 5 条路线仪表板/配置文件...我想做的是在成功登录后进入/dashboard路线,但由于我的想法是动态路线加载,我无法弄清楚如何导航。
在我的上下文中,登录是一个简单的假函数:
try {
setContextState({ type: ContextActions.LOGIN_IN_PROGRESS });
setTimeout(() => {console.log({ userId: 1, username: 'admin@admin.com' });
setContextState({ type: ContextActions.LOGIN_SUCCESS, payload: { user: { userId: 1, username: 'admin@admin.com' } } });
}, 3000);
} catch(error) {
setContextState({ type: ContextActions.LOGIN_ERROR });
}