javascript - window.location.href 与 history.pushState - 使用哪个?

标签 javascript window react-router browser-history

我一直在自学react-router , 现在我想知道应该使用哪种方法转到另一个页面。

根据 this post (Programmatically navigate using react router) , 你可以通过 this.props.history.push('/some/path') 转到另一个页面.

不过,老实说,我不太确定 window.location.href 之间的区别。和 history.pushState .

据我了解,window.location.href = "/blah/blah";通过进行刷新浏览器的新 HTTP 调用将您带到另一个页面。

另一方面,什么history.pushState (和 this.props.history.push('/some/path') )的作用是插入状态。这显然会更改 HTTP 引荐来源网址并因此更新 XMLHttpRequest .

这是来自 mozila's documentation... 的摘录

Using history.pushState() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.

对我来说,听起来这两种方法都进行了新的 HTTP 调用。如果是,有什么区别?

任何建议将不胜感激。

附言

我认为开发人员在决定如何转到另一个页面之前需要考虑是否有必要从服务器获取数据。

如果您需要从服务器检索数据,window.location.href会 没关系,因为您将进行新的 HTTP 调用。但是,如果您使用 <HashRouter> ,或者您想避免为了速度而刷新页面,什么是好的方法?

这个问题促使我发表这篇文章。

最佳答案

history.pushstate 进行新的 HTTP 调用(来自您引用的 mozilla 文档):

Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser.

window.location.href = "url" 将浏览器导航到新位置,因此它确实发出新的 http 请求。 注意:当您将新 url 指定为散列片段时会出现异常(exception)情况。然后窗口就滚动到相应的 anchor


您可以在打开“网络”选项卡的情况下从 devTools 控制台检查是否正在运行它们。请务必启用“保留日志”选项。网络选项卡列出了所有新的 http 请求。

关于javascript - window.location.href 与 history.pushState - 使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47583856/

相关文章:

javascript - 获取有关更改的最新标签数据

Java图形用户界面窗口

reactjs - React 路由器 - 链接主页上的 activeClassName

javascript - 将行为添加到 react-router Link

javascript - 为什么我的 addClass 方法不起作用?

javascript - 使用 Javascript 查找范围值的索引

javascript - window.focus 在 IE 中不起作用

javascript - 未捕获的类型错误 : Cannot read property 'push' of undefined (React-Router-Dom)

javascript - Epiphany GNOME Web 浏览器 2.28.0 在呈现日语日期时挂起

javascript - 使用 Dojo ContentPanel 滚动到特定位置