管理react路由的history对象的插件history的使⽤介绍
本⽂介绍如何使⽤history插件管理浏览记录
1. history插件的使⽤
history这个插件可以⽅便管理你的浏览记录
cnpm install history --save
import createHistory from 'history/createBrowserHistory'
2. 三种⽅法react router6
有三种使⽤⽅式
createBrowserHistory 现代浏览器使⽤
createBrowserHistory({
basename: '', // 基链接
forceRefresh: false, // 是否强制刷新整个页⾯
keyLength: 6, // location.key的长度
getUserConfirmation: (message,callback) => firm(message)) // 跳转拦截函数
})
createMemoryHistory ⼿机端使⽤
createMemoryHistory({
initialEntries: ['/'], // 初始载⼊路径,和MemoryRouter中的initialEntries是⼀样的
initialIndex: 0, // initialEntries初始载⼊索引
keyLength: 6, // location.key的长度
getUserConfirmation: null // 路由跳转拦截函数
})
createHashHistory ⽼版本浏览器使⽤,暂不介绍
3. 基本使⽤功能
const history = createHistory(); 创建历史对象
const location = history.location; 获取location对象
const unlisten = history.listen( (location, action) => {
console.log(location,action)
// location是location对象
// action是动作名称,⽐如 "PUSH"
} )
history.push('/a', { some: 'state' }) // 强制跳转
unlisten() // 监听解绑
4. history对象
属性:
上⾯三种⽅法创建的history对象都有如下三个属性
history.length 历史记录的条数
history.location 历史记录中的location对象
history.action 当前的历史记录是通过什么动作添加进来的,如 "PUSH"
createMemoryHistory中提供了额外的两个属性
history.index 当前历史记录的索引
⽅法
listen⽅法
history.listen( (location,action) => {
console.log(location,action);
// location就是window.location的⼀个⼦集
// action可能的值,"PUSH", "REPLACE", "POP"
} )
5. 使⽤history实现跳转
push
使⽤push可以将⼀条新的历史记录推送到历史堆栈中
history.push('/a');
history.push('/a',{name: 'yejiawei'});
history.push({
pathname: '/a',
state: {
name: 'yejiawei'
}
});
replace⽅法和push⽅法使⽤形式⼀样,replace的作⽤是取代当前历史记录
go,此⽅法⽤来前进或者倒退,(-1);
goBack,此⽅法⽤来回退,Back();
goForward,此⽅法⽤来前进,Forward();
另外使⽤createMemoryHistory创建的history对象,有canGo⽅法,和go⽅法类似
6. 使⽤history实现路由跳转警告
const unblock = history.block('Do you want to leave?');
上⾯这个⽤法,就是添加⼀个跳转提⽰信息,默认使⽤dom环境的firm,所以如果使⽤⾮dom环境的createMemoryHistory就要使⽤getUserConfirmation⽅法实现另外,除了传递⼀个字符串提⽰信息以外,还可以添加函数
const unblock = history.block( (location,action) => {
return 'do you leave?'
} )
可以通过直接调⽤,unblock(); 实现⽅法解绑