简体   繁体   中英

React Router 4: Pass route props to layout component

I'm trying to pass the route props to a layout component which performs initial API requests with the route props, the problem is that these route props are only passed to the child routes.

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

Obviously, once the user hits the /some/:route route, the layout would have been already rendered. I tried doing something like this:

<BrowserRouter>
    <Route path="/some/:route" render={(props) =>
        (<AppLayout {...props}><SomeComponent /></AppLayout>)} />
</BrowserRouter>

This works but the AppLayout would be unmounted and remounted every time I go to another route using the same layout.

With react-router 3, I could do something like this:

<Router history={browserHistory}>
    <Route path="/" component={AppLayout}>
        <Route path="/some/:route" component={SomeComponent} />
        <Route path="/some/other/:route" component={OtherComponent} />
    </Route>
</Router>

And the route props would be available on the AppLayout component.

Is there a way of actually achieving this with react-router 4?

Since you want to nest routes you should do something like this:

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

Notice how I am passing the router props to AppLayout and using the AppLayout component as a handler for both the routes. Now inside the AppLayout component you'll have to mention these routes again with their respective components, like this:

<Switch>
  <Route exact path="/some/:route" render={props => <SomeComponent {...this.props} />} />
  <Route exact path="/some/other/:route" render={props => <OtherComponent {...this.props} />} />
</Switch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM