![](/img/trans.png)
[英]React Router to change route/component without changing browser URL
[英]How to change component with react-router without changing URL in address bar?
我有一个用例。
我的主要反应应用程序(容器)正在加载(安装)另一个反应子应用程序(模块),它是使用react-router
。
当子应用程序中的路由发生更改时,它也会更改主应用程序URL。
有没有办法在不更改URL的情况下更改路由?
我知道这可以在子应用程序中没有react-router
,只需根据状态更改组件。
但是我们怎么能用react-router
实现同样的目标呢?
它应该是一种少头应用,请帮助你的想法。
如果您想在不更改URL的情况下使用react-router
,可以考虑使用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)中很有用。
您只需要知道MemoryRouter
不会更改浏览器历史记录,因此您将无法按下后退按钮。 如果要保留后退按钮,则需要手动处理。
this.props.history.goBack() // when a user click on the back button
this.props.history.goForward() // when a user click the forward button
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.