react-router:如何在不导致导航/重新加载的情况下更新URL? [英] react-router: How do I update the url without causing a navigation/reload?

查看:46
本文介绍了react-router:如何在不导致导航/重新加载的情况下更新URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用React Router,我已经完成了网址更新:

With react router I have done this up update the url:

this.props.history.push({
            pathname: `/product/${this.props.product.id}`,
        });

但是,这会导致重新渲染/导航更改.有没有一种方法可以不执行此操作来更新url?

However this causes a re-render/navigation change. Is there a way to update the url without doing that?

我的用例是我有一个产品列表,当我单击一个产品时,我显示一个Modal,并希望将URL更新为example.com/product/1之类的内容,以便链接可以共享.

My use case is I have a list of products and when I click on one I show a Modal and want to update the url to something like example.com/product/1 so that the link is sharable.

推荐答案

无法使用React Router找到解决方案,但能够通过使用浏览器的历史记录界面通过调用以下方法来完成此任务:

Wasn't able to find a solution using React Router, but was able to accomplish this using the browser's history interface by calling:

window.history.replaceState(null, "New Page Title", "/pathname/goes/here")

您可以了解有关 .replaceState 的更多信息

You can learn more about .replaceState here.

反应路由器的 history.replace 并不总是有效

React Router's history.replace won't always work

React Router的 history.replace 方法可能会或可能不会触发重新渲染,具体取决于您应用的路由设置(例如,您拥有全部/* 路由)).它不会阻止按定义进行渲染.

React Router's history.replace method may or may not trigger a re-render depending on your app's route setup (e.g., you have a catch-all /* route). It does not prevent a render by definition.

这篇关于react-router:如何在不导致导航/重新加载的情况下更新URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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