我有一个声明一些路由的 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 的dumb组件,可以调用 <Route component={component} />
或 <Redirect to={to} />
,但最后会调用 component
方法)
基本上每个组件都是在路线更改时安装/卸载的。我想保留这个方面除了 Dashboard
路线可以做很多事情,并且我希望不在仪表板上卸载一次(假设您到达 session 页面,您还不需要安装仪表板),但是一旦加载了仪表板,当您进入您的个人资料页面、 session 或其他任何内容,当您返回仪表板时,组件无需再次安装。
我在 React-router 文档上读到 render或者 child 可能是解决方案,而不是组件,但是我们可以将路由与 child 混合使用,将其他路由与组件混合使用吗?我尝试了很多事情,但从未实现我想要的,即使有 render
或children
,我的Dashboard
组件仍在安装/卸载。
最佳答案
Switch
组件仅渲染一条路线,最早匹配的获胜。由于 Dashboard
组件位于其中,因此每当另一个路由匹配时它就会被卸载。将此 Route
移到外部,它将按预期与 render
或 children
一起工作。
关于javascript - React-router:一旦安装了路由上的组件,即使路由发生变化,也永远不会卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917133/