React Router嵌套路由

时间:2018-08-03 09:49:37

标签: javascript reactjs react-router frontend

我有路线:

<Switch>
  <Route path="/about" component={About} />
  <Route path="/about/Us" component={AboutUs} />
  <Route path="/about/Company" component={AboutCompany} />
</Switch>

我希望/ about路线显示关于组件及其子级(AboutUs和AboutCompany),但是/ about路线仅呈现About组件。我该如何解决?我有反应路由器4

2 个答案:

答案 0 :(得分:1)

<Switch>
   <Route exact path="/about" component={About} />
   <Route path="/about/Us" component={AboutUs} />
   <Route path="/about/Company" component={AboutCompany} />
</Switch>

您需要将完全相同的关键字添加到关于父路径。

答案 1 :(得分:0)

有两种方法可以实现它。

  1. 从route.js / jsx创建嵌套路由
  2. 从父组件(about.js / jsx)创建嵌套路由

如果来自routes.js / jsx

<Switch>
  <Route path="/about" component={About}>
    <Route path="/about/Us" component={AboutUs} />
    <Route path="/about/Company" component={AboutCompany} />
  </Route>
</Switch>

如果来自routes.js / jsx

//Routes.jsx/js
<Switch>
  <Route path="/about" component={About} />
</Switch>

//About.jsx/js
<Switch>
    <Route path="/about/Us" component={AboutUs} />
    <Route path="/about/Company" component={AboutCompany} />
</Switch>