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

IT技术 javascript reactjs react-router
2021-05-21 10:02:49

我有一个用例。

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

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

有没有办法在不改变URL的情况下改变路由?

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

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

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

1个回答

如果您想在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