gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:58:17 25 4
gpt4 key购买 nike

我有一个用例。

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

当子应用程序中的路由更改时,它也会更改主应用程序的 URL。

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

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

但是我们怎样才能用 react-router 实现同样的效果呢?

应该是head less application的那种,请大家帮忙出出主意。

最佳答案

如果您想在不更改 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')}

A router that keeps the history of your "URL" in memory (does not read or write to the address bar). Useful in tests and non-browser environments like 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

关于javascript - 如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52640075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com