React-router:永远不要在路由上卸载组件,即使路由发生变化

React-router: never unmount a component on a route once mounted, even if route change

我有一个声明了一些路由的 React 应用程序:

<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 是一个哑组件,它检查 session,然后调用 <Route component={component} /><Redirect to={to} />,但最后,component 方法是调用)

基本上每个组件都是 mounted/unmounted 路线变更。我想为 Dashboard 路线保留 except 方面,它做了很多事情,并且我希望一旦不在仪表板上就被卸载(假设你到达会议页面时,您还不需要安装仪表板)但是一旦加载了仪表板,当您进入个人资料页面、会议或其他任何内容时,当您返回仪表板时,组件不必再次挂载

我在 React-router 文档上读到 render 或 children 可能是解决方案,而不是组件,但我们可以将路由与 children 混合使用,而其他路由与组件混合使用吗?我尝试了很多东西,但从未实现我想要的,即使使用 renderchildren,我的仪表板组件仍然是 mounting/unmounting.

感谢您的帮助

Switch 组件只渲染一条路线,最早的匹配者获胜。由于 Dashboard 组件在其中,只要匹配到另一条路由,它就会被卸载。将此 Route 移到外面,它将按预期与 renderchildren 一起工作。