如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件?



我有一个用例。

我的主要 react 应用程序(容器(正在加载(挂载(另一个 react 子应用程序(模块(,它是使用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 这样的环境。

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

相关内容

最新更新