React-router:一旦安装,永远不要在路由上卸载组件,即使路由发生变化 [英] React-router: never unmount a component on a route once mounted, even if route change

查看:28
本文介绍了React-router:一旦安装,永远不要在路由上卸载组件,即使路由发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 是一个检查会话的哑组件,要么调用 <Route component={component}/> 要么 <Redirect to={to}/>,但最后调用了component方法)

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

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

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.

我在 React-router 文档中阅读了 render 或孩子可能是解决方案,而不是组件,但是我们可以将路由与孩子和其他与组件混合使用吗?我尝试了很多东西,但从未达到我想要的效果,即使使用 renderchildren,我的 Dashboard 组件仍在安装/卸载.

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.

感谢您的帮助

推荐答案

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

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.

这篇关于React-router:一旦安装,永远不要在路由上卸载组件,即使路由发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆