我想在单个路由文件中实现嵌套路由和侧边栏路由的某种组合。 我希望组件像这样呈现。
"/" --- Registration page
"/login" ---- Login Page
"/application" --- Application Page
"/dashboard" --- Dashboard page with Sidebar and Application components
"/dashboard/application" --- Dashboard page with Sidebar and Application components
"/dashboard/user" --- Dashboard page with Sidebar and User components
我的路线设置如下
<Switch>
<Route path="/" component={withAuth(Registration)} />
<Route path="/login" component={withAuth(Login)} />
<Route path={'/dashboard'} component={withAuth(Dashboard)}/>
</Switch>
在仪表板页面内,我基本上实现了 sidebar example来自 react-router-dom 网站。
它工作正常,但我想将所有路由放在一个文件中。
像这样
<Switch>
<Route path="/" component={withAuth(Registration)} />
<Route path="/login" component={withAuth(Login)} />
<Route path={'/dashboard'} component={withAuth(Dashboard)} children={[Sidebar, Application]}/>
<Route path="/dashboard/application" component={withAuth(Dashboard)} children={[Sidebar, Application]}/>
<Route path="/dashboard/user" component={withAuth(Dashboard)} children={[Sidebar, User]}/>
</Switch>
上面的代码是虚构的代码,但它是为了让您了解我正在努力实现的目标。我尝试了类似 question 的解决方案,但它对我不起作用。
我如何将所有路由放在一个文件中并处理 react-router-dom v4/v5 中的侧边栏路由和嵌套路由?
我创建了一个 example code sandbox , 请试试 this示例。
最佳答案
虽然我认为将所有路由放在一个文件中已成为一种反模式,但我认为您可以获得与您正在寻找的东西足够接近的东西 - 具体来说,让所有路由驻留在同一个文件中。
主要技巧是像 normal switch 一样使用开关. Switch
中的最后一个案例成为默认案例(或路由)。
您还需要使用 exact因为没有它,它每次都会匹配 URL /
。 InternalRoutes
中的第二个 Switch
也是如此。如果您不包含 exact
,它将每次都匹配 /dashboard
并且永远不会到达 /dashboard/application
或 dashboard/用户
。您仍然需要将 Routes
组件包装在 BrowserRouter
组件中。
import React from 'react';
import { Switch, Route } from 'react-router-dom';
const Routes = props => {
return (
<Switch>
<Route exact path="/" component={withAuth(Registration)} />
<Route exact path="/login" component={withAuth(Login)} />
<Route component={withAuth(InternalRoutes)} />
</Switch>
);
};
const InternalRoutes = props => {
return (
<Switch>
<Route exact path="/dashboard" component={withAuth(Dashboard)} children={[Sidebar, Application]}/>
<Route exact path="/dashboard/application" component={withAuth(Dashboard)} children={[Sidebar, Application]}/>
<Route exact path="/dashboard/user" component={withAuth(Dashboard)} children={[Sidebar, User]}/>
<Route component={NotFoundComponent} />
);
};
const NotFoundComponent = props => {
return <div>URL Not Found</div>;
};
export default Routes;
关于reactjs - 使用 react-router-dom v4/v5 组合侧边栏和嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58405540/