注意:addEventListener()和removeEventListener()需要调用同一个函数
错误用法示例:函数写法虽然一样,但是实际上调用的不是同一个函数
window.addEventListener('popstate', function (event) {
window.history.go(-2);
});
window.removeEventListener('popstate', function (event) {
window.history.go(-2);
});
正确用法:
componentDidMount(){
//拦截安卓回退按钮
let me = this;
// 页面载入时使用pushState插入一条历史记录
// history.pushState(null, null, location.href);
window.addEventListener('popstate', me.backRouter);
}
//组件移除
componentWillUnmount(){
// console.log('componentWillUnmount')
let me = this;
//在addEventListener()和removeEventListener()中用的是相同的函数backRouter
window.removeEventListener('popstate',me.backRouter)
}
//返回自定义的路由
backRouter(){
window.history.go(-2);
}
history.back()和history.go()的区别
go(-1): 返回上一页,原页面表单中的内容会丢失;history.go(-1):后退+刷新;history.go(1) :前进
back(): 返回上一页,原页表表单中的内容会保留; history.back():后退 ; history.back(0) 刷新; history.back(1):前进
如果用back 会保留之前页面的内容,看到的效果就是在回退时中间的页面会闪一下,用go就不会出现中间的页面闪现的问题