使用react-router-dom v4 / v5组合侧边栏和嵌套路由

时间:2019-10-16 03:55:16

标签: reactjs routing react-router react-router-v4 react-router-dom

我想在单个路由文件中实现嵌套路由和侧边栏路由的某种组合。 我希望这些组件能够像这样渲染。

"/" --- 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>

在仪表板页面中,我基本上已经从react-router-dom网站实现了sidebar example

它工作正常,但是我要将所有路由都放在一个文件中。

类似这样的东西

<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示例。

1 个答案:

答案 0 :(得分:1)

尽管我认为将所有路由都放在一个文件中已经成为反模式,但我认为您可以实现与所需内容足够接近的东西-具体来说,就是将所有路由都保存在同一文件中。

主要技巧是像normal switch一样使用开关。 Switch中的最后一个大小写成为默认大小写(或路由)。

您还需要使用exact,因为没有它,它将每次都与URL /相匹配。 Switch中第二个InternalRoutes的情况也是如此。如果您不包括exact,它将每次都匹配/dashboard,并且永远不会到达/dashboard/applicationdashboard/user。您仍然需要将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;