【问题标题】:React Router 4: Pass route props to layout componentReact Router 4:将路由道具传递给布局组件
【发布时间】: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 实现这一点?

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

既然你想嵌套路由,你应该这样做:

<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>

【讨论】:

  • 谢谢,这似乎奏效了,虽然它似乎适得其反,特别是因为以前可以通过更简单的方法来实现。
  • 是的,确实适得其反。使用 react router 3 处理路由更加简单直接。
猜你喜欢
  • 2018-04-25
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 2018-06-17
  • 2019-06-08
相关资源
最近更新 更多