【发布时间】:2018-05-19 19:33:06
【问题描述】:
我正在尝试将路由道具传递给布局组件,该组件使用路由道具执行初始 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 实现这一点?
【问题讨论】:
-
一定要看看 react-router 的
matchPath
标签: javascript reactjs react-router