首页 > 解决方案 > 如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件?

问题描述

我有一个用例。

我的主要反应应用程序(容器)正在加载(安装)另一个反应子应用程序(模块),它是使用react-router.

当子应用程序中的路由发生变化时,它也改变了主应用程序的 URL。

有什么方法可以在不更改 URL 的情况下更改路由?

我知道这在没有react-router子应用程序的情况下是可能的,只需根据状态更改组件即可。

但是我们怎样才能达到同样的效果react-router呢?

它应该是一种无头应用程序,请帮助您的想法。

标签: javascriptreactjsreact-router

解决方案


如果您想在react-router不更改 URL 的情况下使用,您可以考虑使用MemoryRouter

import { MemoryRouter } from 'react-router';
<MemoryRouter>
     <div>
       <Route path="/first" component={FirstComponent} />
       <Route path="/second" component={SecondComponent} />
     </div>
 </MemoryRouter>

并像往常一样使用它:

this.props.history.push('/second')}

将您的“URL”历史记录在内存中的路由器(不读取或写入地址栏)。在测试和非浏览器环境(如 React Native)中很有用。

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/MemoryRouter.md

您只需要注意MemoryRouter不会更改浏览器历史记录,因此您将无法按下后退按钮。如果要保留后退按钮,则需要手动处理。

this.props.history.goBack() // when a user click on the back button
this.props.history.goForward() // when a user click the forward button

推荐阅读