React-router: never unmount a component on a route

2019-04-07 12:35发布

问题:

I have a React application that declares some routes :

     <Switch>
      <Route exact path={'/'} render={this.renderRootRoute} />
      <Route exact path={'/lostpassword'} component={LostPassword} />
      <AuthenticatedRoute exact path={'/profile'} component={Profile} session={session} redirect={'/'} />
      <AuthenticatedRoute path={'/dashboard'} component={Dashboard} session={session} redirect={'/'} />
      <AuthenticatedRoute path={'/meeting/:meetingId'} component={MeetingContainer} session={session} redirect={'/'} />
      <Route component={NotFound} />
    </Switch>

(AuthenticatedRoute is a dumb component that checks the session, and either call <Route component={component} /> or <Redirect to={to} />, but at last, component method is invoked)

Where basically each component is mounted/unmounted on route change. I'd like to keep that aspect except for the Dashboard route which does a lot of things, and that I would like to be unmounted once not on dashboard (let's say you arrive on a meeting page, you do not need to mount your dashboard yet) but once you loaded once your Dashboard, when you go on your profile page, a meeting or whatever, when you go back on your Dashboard the component does not have to mount again.

I read on React-router doc that render or children might be the solution, instead of component, but could we mix routes with children and other with component? I tried many things and never achieved what I wanted, even with render or children, my Dashboard component is still mounting/unmounting.

Thanks for your help

回答1:

The Switch component only ever renders a single route, the earliest match wins. As the Dashboard component is inside it, it gets unmounted whenever another route gets matched. Move this Route outside and it will work as intended with render or children.