- 深入理解React Router:从原理到实践
- 李杨韬
- 268字
- 2025-02-26 04:47:01
1.3.6 window.location.replace
与history.replaceState类似,window.location.replace会替换当前的栈记录,但在设置绝对路径时,其会刷新页面,重新加载传入的URL。其语法为:

与设置href不同的是,用replace替换了新页面后,旧页面记录不会被保存。在历史栈记录中,这意味着用户将不能用“后退”按钮再次回到旧页面。

在上面的例子中,由于在b.com中调用了location.replace方法,b.com的页面记录将消失,替换为c.com的页面记录。当用户在c.com页面单击浏览器的“后退”按钮时,将回到a.com页面。
在某些有表单元素的页面下,用户刷新页面会有POST数据的提交,如果想要刷新当前的页面,同时避免POST数据的提交,则可以使用:

对于window.location.replace,同样可使用相对路径进行跳转,跳转规则与1.2.3节中介绍的一致。