如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件? [英] How to change component with react-router without changing URL in address bar?

查看:49
本文介绍了如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例.

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

My main react application (container) is loading (mounting) another react child application (module), which is implemented using react-router.

当子应用中的路由改变时,它也在改变主应用的 URL.

When the route changes in the child application, it is also changing the main application URL.

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

Is there any way to change the route without changing URL?

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

I know this is possible without react-router in the child application, by just changing component based on state.

但是我们如何使用 react-router 实现相同的效果?

But how can we achieve the same with react-router?

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

It should be kind of head less application, please help your thoughts.

推荐答案

如果你想使用 react-router 而不改变 URL 你可以考虑使用 MemoryRouter

If you want to use react-router without changing the URL you may consider using a MemoryRouter

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

</MemoryRouter>

And use it like usual:

并像往常一样使用它:



<块引用>

一个将您的URL"历史记录保存在内存中的路由器(不会读取或写入地址栏).在测试和非浏览器中有用像 React Native 这样的环境.

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 不会更改浏览器历史记录,因此您将无法按后退按钮.如果您想保留后退按钮,则需要手动处理.

You just need to be aware that MemoryRouter does not change the browser history, thus you won't be able to press the back button. If you want to keep a back button, you will need to handle it manually.

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

这篇关于如何在不更改地址栏中的 URL 的情况下使用 react-router 更改组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆