javascript - React Router如何处理url变化而不引起浏览器请求

标签 javascript reactjs react-router

据我了解,到目前为止,像 Angular JS、Backbone JS 这样的前端框架都在使用哈希值。但react router并不一定需要hash。有人可以解释一下这是如何工作的吗?

我想这一定很简单,可能会阻止 URL 更改时的默认行为。

我不知道!

最佳答案

它被称为“推送状态路由”,它利用 HTML5 History API

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

Suppose http://mozilla.org/foo.html executes the preceding JavaScript:

This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.

Suppose now that the user now navigates to http://google.com, then clicks back. At this point, the URL bar will display http://mozilla.org/bar.html, and the page will get a popstate event whose state object contains a copy of stateObj. The page itself will look like foo.html, although the page might modify its contents during the popstate event.

If we click back again, the URL will change to http://mozilla.org/foo.html, and the document will get another popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

一旦我们理解了这一切,我们只需要监听窗口的 popstate 事件,该事件将在每次状态更改时触发,无论是通过点击、按浏览器后退按钮等触发。

关于javascript - React Router如何处理url变化而不引起浏览器请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45734035/

相关文章:

reactjs - react 映射错误 :"Did you wrap <GoogleMap> component with withGoogleMap() HOC?"

reactjs - React 路由器 v.5.3.0 : route component doesn't display

reactjs - 具有相似路径(固定和动态路径参数)的 React Router v4 组件为 "overlapping"

javascript - 随机化两个数组中的链接元素 Discord.js

javascript - 在 PHP 中发送请求之前将用户数据附加到 url

javascript - 用 Canvas 绘图时如何在两点之间进行插值?

javascript - 预期语法错误 : Unexpected token,,(10:10)

reactjs - 部署错误 : Argument of type 'MiniCssExtractPlugin' is not assignable to parameter of type 'Plugin'

reactjs - React Router 中的 matchPath 似乎没有考虑 Basename

javascript - jQuery 调整窗口对象