react-router:如何在不导致导航/重新加载的情况下更新URL? [英] react-router: How do I update the url without causing a navigation/reload?
问题描述
使用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")
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屋!