Skip to content

Commit 701f9a4

Browse files
committed
route
1 parent 279e17c commit 701f9a4

File tree

2 files changed

+32
-14
lines changed

2 files changed

+32
-14
lines changed

route/JS路由原理.md

+29-14
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,22 @@
44

55
## 1.1 比较两种
66
1. 是否需要服务器支持?
7-
- hash不需要,因为`#hash`并没有改变url的地址,始终指向同一个地址,可以静态部署
8-
- history需要,url改变了,需要服务器把所有路由都重定向到根页面
7+
- hash不需要,因为`#hash`并没有改变url的地址,始终指向同一个地址,可以静态部署
8+
- history需要,url改变了,需要服务器把所有路由都重定向到根页面
99
2. 用户访问url或手动刷新时?
10-
- hash:始终返回同一个html,静态地址即可
11-
- history:访问非根目录的路由时,需要后端重定向到根页面,并返回根页面的html
10+
- hash:始终返回同一个html,静态地址即可
11+
- history:访问非根目录的路由时,需要后端重定向到根页面,并返回根页面的html
1212
3. 用户在页面内进行跳转时?
13-
- 都不会向服务器发起请求,执行内部的js代码
13+
- 都不会向服务器发起请求,执行内部的js代码
1414
4. 跳转的参数
15-
- hash:hash值就是参数,参数携带在url中
16-
- history:参数携带在state中
15+
- hash:hash值就是参数,参数携带在url中
16+
- history:参数携带在state中
17+
18+
## 1.2 三种行为对应的事件
19+
1. 页面加载或刷新:触发onload事件
20+
2. 相同url下改变hash:触发hashchange事件
21+
3. history路由切换:无官方事件触发
22+
4. 导航的前进后退:触发onpopstate事件
1723

1824
## 现象1:在https://lemonc747.github.io/react-playground/内路由跳转可以正常跳转,但刷新后就github-404页面了?
1925
因为`github.io`上是静态的html,访问根页面时,url指向根页面的地址正确。
@@ -25,7 +31,6 @@
2531
在url中添加`#[hash]`,即可改变url的hash值。
2632

2733
原理:通过监听全局的`hashChange`事件,当url的hash改变时进行判断和匹配
28-
2934
![](./assets/hash_route.jpeg)
3035

3136
```ts
@@ -46,15 +51,25 @@ window.onhashchange = () => {
4651
location.hash = "#hash1";
4752
```
4853

49-
### hash路由的应用
50-
### hash注意点
51-
1. 改变url的hash值,不会触发页面的重新加载(load事件),会触发hashchange事件
52-
5354
# 三 history路由
54-
在保持url同源的情况下,改变url。
55-
5655
![](./assets//history_route.jpeg)
5756

57+
## 3.1 history api
58+
[reference:MDN-history](https://developer.mozilla.org/en-US/docs/Web/API/History)
59+
60+
- forward: 导航前进
61+
- back: 导航后退
62+
- go: 导航前进或后退几页
63+
- pushState: 添加新的历史记录
64+
- replaceState: 修改当前页的历史记录
65+
- onpopstate: 导航前进或后退时触发,获取当前历史记录携带的state数据
66+
67+
### pushState
68+
```ts
69+
(method) History.pushState(data: any, unused: string, url?: string | URL | null | undefined): void
70+
```
71+
72+
5873

5974
# 四 浏览器URL跳转原理
6075

route/react-router.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# react-router
2+
3+
## 主要概念 main concept

0 commit comments

Comments
 (0)