使用React Router v4重复路由

时间:2018-04-21 17:29:55

标签: reactjs react-router-v4

在嵌套组件中重复路由是一种好方法吗?

<App>
   <Route exact path="/" render={props =>
      <Layout>
         <Route exact path="/" component={ComponentUnderLayout} />
         <Route exact path="/path1" component={ComponentUnderLayout2} /> 
      </Layout>
   } />
   <Route path="/signin" component={ComponentWithoutLayout} />
</App>

我不确定它是最好的解决方案。正如你所看到的,我将包括我的应用程序的所有组件,除了其中一些。我想为除/ signin和/ signup之外的所有路径渲染Layout和Header。

也许有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

我很关心你的代码:1。渲染是一个函数:

<Route exact path="/" render={props =>
   <Layout>
      <Route exact path="/" component={ComponentUnderLayout} />
      <Route exact path="/path1" component={ComponentUnderLayout2} /> 
   </Layout>
} />

2。永远不会呈现ComponentUnderLayout2

<Route exact path="/" render={props =>
   {/* you have declared that this will get render ONLY when URL is exactly ` "/" which means "/path1" will never get to this place */}
   <Layout>
      <Route exact path="/" component={ComponentUnderLayout} />
      <Route exact path="/path1" component={ComponentUnderLayout2} /> 
   </Layout>
} />

因此,如果你在上面纠正,你最终会得到:

<App>
   <Route exact path="/" render={(props) => 
      <Layout>
         <ComponentUnderLayout {...props} />
      </Layout>
   } />
   <Route path="/path1" render={props => 
      <Layout>
         <ComponentUnderLayout2 {...props} />
      </Layout>
   } /> 
   <Route path="/signin" component={ComponentWithoutLayout} />
</App>

编辑:

<App>
   <Layout>
     <Route exact path="/" component={ComponentUnderLayout} />
     <Route exact path="/path1" component={ComponentUnderLayout2} />
   </Layout>
   <Route exact path="/signin" component={ComponentWithoutLayout} />
</App>