React Router 是一個基於 React 之上的強大路由庫,它可以讓你向應用中快速地添加視圖和數據流,同時保持頁面與 URL 間的同步。本文從兩個方便來解析 react-router 實現原理。一:介紹 react-router 的依賴庫history;二:使用 history 庫,實現一個簡單的 react-router 路由。
history 介紹
前端精品教程:百度網盤下載
history 是一個 JavaScript 庫,可讓您在 JavaScript 運行的任何地方輕松管理會話歷史記錄。history 抽象出各種環境中的差異,並提供最小的 API ,使您可以管理歷史堆棧,導航,確認導航以及在會話之間保持狀態。
history 有三種實現方式:
1、BrowserHistory:用於支持 HTML5 歷史記錄 API 的現代 Web 瀏覽器(請參閱跨瀏覽器兼容性)
2、HashHistory:用於舊版Web瀏覽器
3、MemoryHistory:用作參考實現,也可用於非 DOM 環境,如 React Native 或測試
三種實現方法,都是創建了一個 history 對象,這里主要講下前面兩種:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
const history = {
length: globalHistory.length,
action:
"POP"
,
location: initialLocation,
createHref,
push,
// 改變location
replace,
go,
goBack,
goForward,
block,
listen
//監聽路由變化
};
|
1.頁面跳轉實現
前端精品教程:百度網盤下載
BrowserHistory:pushState、replaceState;
HashHistory:location.hash、location.replace
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
function
push(){
createKey();
// 創建location的key,用於唯一標示該location,是隨機生成的
if
(BrowserHistory){
globalHistory.pushState({ key, state },
null
, href);
}
else
if
(HashHistory){
window.location.hash = path;
}
//上報listener 更新state ...
}
function
replace(){
createKey();
// 創建location的key,用於唯一標示該location,是隨機生成的
if
(BrowserHistory){
globalHistory.replaceState({ key, state },
null
, href);
}
else
if
(HashHistory){
window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) +
"#"
path);
}
//上報listener 更新state ...
}
|
2.瀏覽器回退
BrowserHistory:popstate;
HashHistory:hashchang;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
if
(BrowserHistory){
window.addEventListener(
"popstate"
, routerChange);
}
else
if
(HashHistory){
window.addEventListener(
"hashchange"
, routerChange);
}
function
routerChange(){
const location = getDOMLocation();
//獲取location
//路由切換
transitionManager.confirmTransitionTo(location,callback=()=>{
//上報listener
transitionManager.notifyListeners();
});
}
|
通過 history 實現簡單 react-router
前端精品教程:百度網盤下載
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import { Component } from
'react'
;
import createHistory from
'history/createHashHistory'
;
const history = createHistory();
//創建 history 對象
/**
* 配置路由表
* @type {{"/": string}}
*/
const router = {
'/'
:
'page/home/index'
,
'/my'
:
'page/my/index'
}
export
default
class Router extends Component {
state = { page:
null
}
async route(location) {
let pathname = location.pathname;
let pagePath = router[pathname];
// 加 ./的原因 https://webpack.docschina.org/api/module-methods#import-
const Page = await import(`./${pagePath}`);
//獲取路由對應的ui
//設置ui
this
.setState({
Page: Page.
default
});
}
initListener(){
//監聽路由切換
history.listen((location, action) => {
//切換路由后,更新ui
this
.route(location);
});
}
componentDidMount() {
this
.route(history.location);
this
.initListener();
}
render() {
const { Page } =
this
.state;
return
Page && <Page {...
this
.props} />;
}
}
|
目前react-router在項目中已有大量實踐,其優點可以總結如下:
風格: 與React融為一體,專為react量身打造,編碼風格與react保持一致,例如路由的配置可以通過component來實現
簡單: 不需要手工維護路由state,使代碼變得簡單
強大: 強大的路由管理機制,體現在如下方面
- 路由配置: 可以通過組件、配置對象來進行路由的配置
- 路由切換: 可以通過<Link> Redirect進行路由的切換
- 路由加載: 可以同步記載,也可以異步加載,這樣就可以實現按需加載
使用方式: 不僅可以在瀏覽器端的使用,而且可以在服務器端的使用
當然react-router的缺點就是API不太穩定,在升級版本的時候需要進行代碼變動。
