react-router:如何在不导致导航/重新加载的情况下更新 url? [英] react-router: How do I update the url without causing a navigation/reload?
问题描述
使用反应路由器我已经完成了更新网址:
With react router I have done this up update the url:
this.props.history.push({
pathname: `/product/${this.props.product.id}`,
});
然而,这会导致重新渲染/导航更改.有没有办法在不这样做的情况下更新网址?
However this causes a re-render/navigation change. Is there a way to update the url without doing that?
我的用例是我有一个产品列表,当我点击一个产品列表时,我会显示一个模态并希望将 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.
React Router 的 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屋!