现在的登录页一般会有多个状态,页面会有按钮提供给用户切换,但是产品要求使用浏览器回退时也要让界面回退,对于浏览器来说,页面没有历史,所以不会改变,所以我们要手动添加来达到效果
let historyArr = []; // 本地记录history
class LoginDj extends React.Component {
//验证码登录/扫描登录/注册切换时
shiftLoginType(type) {
this.setState(
{
curLoginType: type,//多个状态写在一个页面当然会有个值表示现在是显示登录/注册/或者其他
},
() => {
//在回调中调用,防止state值延迟
this.addHistoryEntity();
}
);
}
//新增一条浏览器浏览历史记录
addHistoryEntity() {
if (history.pushState) {
//现代浏览器
history.pushState(this.state.curLoginType, null, document.URL);
historyArr.push(this.state.curLoginType);
} else {
//ie9及以下
historyArr.push(this.state.curLoginType);
document.getElementById("goFoo").click();
}
}
//监听浏览器回退按钮
detectBack() {
if (history.pushState) {
//现代浏览器
window.onpopstate = () => {
this.logout();
};
} else {
//ie9及以下
$(window).on("hashchange", () => {
if (location.hash == "") {
return;
}
this.logout();
});
}
}
//回退前事件
logout() {
// 本地记录只有一个了要停止修改
if (historyArr.length === 1) return;
将curLoginType回退到上一次的记录
this.setState({
curLoginType: historyArr[historyArr.length - 2],
});
historyArr.splice(historyArr.length - 1, 1);
}
}
componentDidMount() {
this.addHistoryEntity();//开启监听
this.detectBack(); // 回退监听
}
componentWillUnmount() {
window.onpopstate = null;//清除监听
}