【发布时间】:2021-08-10 04:09:55
【问题描述】:
这是我根据上下文中的用户对象加载路由(反应路由器 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 上,成功登录后,我得到了路线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 });
}
【问题讨论】:
标签: reactjs react-router react-router-dom