我正在尝试将路径道具传递给布局组件,该组件使用路径道具执行初始API请求,问题是这些路径道具只传递给子路径 .
<BrowserRouter>
<Switch>
<AppLayout> // This AppLayout performs API requests
// with the :route param in the child routes.
<Route path="/some/:route" component={SomeComponent} />
<Route path="/some/other/:route" component={OtherComponent} />
</AppLayout>
</Switch>
</BrowserRouter>
显然,一旦用户点击 /some/:route
路线,布局就已经被渲染了 . 我尝试过这样的事情:
<BrowserRouter>
<Route path="/some/:route" render={(props) =>
(<AppLayout {...props}><SomeComponent /></AppLayout>)} />
</BrowserRouter>
这可以工作,但每次我使用相同的布局去另一条路线时,AppLayout将被卸载并重新安装 .
使用react-router 3,我可以这样做:
<Router history={browserHistory}>
<Route path="/" component={AppLayout}>
<Route path="/some/:route" component={SomeComponent} />
<Route path="/some/other/:route" component={OtherComponent} />
</Route>
</Router>
并且路径道具将在AppLayout组件上可用 .
有没有办法用react-router 4实现这个目标?
1 回答
既然你想要嵌套路线,你应该做这样的事情:
注意我如何将路由器道具传递给
AppLayout
并使用AppLayout
组件作为两个路由的处理程序 . 现在在AppLayout
组件中,您将不得不再次使用它们各自的组件来提及这些路由,如下所示: