gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:50:08 24 4
gpt4 key购买 nike

据我了解,到目前为止,像 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com