# 一、React Router基础之history
# 1.1 History介绍
history是一个独立的第三方js库,可以用来兼容在不同浏览器、不同环境下对历史记录的管理,拥有统一的API。具体来说里面的history分为三类
- 老浏览器的
history: 主要通过hash来实现,对应createHashHistory - 高版本浏览器: 通过
html5里面的history,对应createBrowserHistory node环境下: 主要存储在memeory里面,对应createMemoryHistory
上面针对不同的环境提供了三个
API,但是三个API有一些共性的操作,将其抽象了一个公共的文件createHistory
// 内部的抽象实现
function createHistory(options={}) {
...
return {
listenBefore, // 内部的hook机制,可以在location发生变化前执行某些行为,AOP的实现
listen, // location发生改变时触发回调
transitionTo, // 执行location的改变
push, // 改变location
replace,
go,
goBack,
goForward,
createKey, // 创建location的key,用于唯一标示该location,是随机生成的
createPath,
createHref,
createLocation, // 创建location
}
}
@前端进阶之旅: 代码已经复制到剪贴板
上述这些方式是
history内部最基础的方法,createHashHistory、createBrowserHistory、createMemoryHistory只是覆盖其中的某些方法而已。其中需要注意的是,此时的location跟浏览器原生的location是不相同的,最大的区别就在于里面多了key字段,history内部通过key来进行location的操作
function createLocation() {
return {
pathname, // url的基本路径
search, // 查询字段
hash, // url中的hash值
state, // url对应的state字段
action, // 分为 push、replace、pop三种
key // 生成方法为: Math.random().toString(36).substr(2, length)
}
}
@前端进阶之旅: 代码已经复制到剪贴板
# 1.2 内部解析
三个
API的大致的技术实现如下
createBrowserHistory: 利用HTML5里面的historycreateHashHistory: 通过hash来存储在不同状态下的history信息createMemoryHistory: 在内存中进行历史记录的存储`
# 1.2.1 执行URL前进
createBrowserHistory:pushState、replaceStatecreateHashHistory:location.hash=*** location.replace()createMemoryHistory: 在内存中进行历史记录的存储
// 伪代码
// createBrowserHistory(HTML5)中的前进实现
function finishTransition(location) {
...
const historyState = { key };
...
if (location.action === 'PUSH') ) {
window.history.pushState(historyState, null, path);
} 