React Router 是一个基于 React 之上的强大路由库,它可让你向应用中快速地添加视图和数据流,同时保持页面与 URL 间的同步。本文从两个方便来解析 react-router 实现原理。一:介绍 react-router 的依赖库history;二:使用 history 库,实现一个简单的 react-router 路由。前端
history 介绍react
前端精品教程:百度网盘下载webpack
history 是一个 JavaScript 库,可以让您在 JavaScript 运行的任何地方轻松管理会话历史记录。history 抽象出各类环境中的差别,并提供最小的 API ,使您能够管理历史堆栈,导航,确认导航以及在会话之间保持状态。web
history 有三种实现方式:api
一、BrowserHistory:用于支持 HTML5 历史记录 API 的现代 Web 浏览器(请参阅跨浏览器兼容性)
二、HashHistory:用于旧版Web浏览器
三、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.页面跳转实现react-router
前端精品教程:百度网盘下载异步
BrowserHistory:pushState、replaceState;async
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,使代码变得简单
强大: 强大的路由管理机制,体如今以下方面
使用方式: 不只能够在浏览器端的使用,并且能够在服务器端的使用
固然react-router的缺点就是API不太稳定,在升级版本的时候须要进行代码变更。