[英]Pass variable on component props of Route in 'react-router-dom'
[英]React Router 4: Pass route props to layout component
我正在尝试将路线道具传递给布局组件,该组件通过路线道具执行初始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实际实现?
由于要嵌套路线,因此应执行以下操作:
<BrowserRouter>
<Switch>
<Route exact path="/" render={props => <AppLayout {...this.props} />} />
<Route exact path="/some/:route" component={AppLayout} />
<Route exact path="/some/other/:route" component={AppLayout}/>
</Switch>
</BrowserRouter>
请注意,我如何将路由器道具传递到AppLayout
以及如何将AppLayout
组件用作两条路线的处理程序。 现在,在AppLayout
组件内,您必须再次提及这些路由及其各自的组件,如下所示:
<Switch>
<Route exact path="/some/:route" render={props => <SomeComponent {...this.props} />} />
<Route exact path="/some/other/:route" render={props => <OtherComponent {...this.props} />} />
</Switch>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.