登录注册同一页面使用浏览器回退功能

现在的登录页一般会有多个状态,页面会有按钮提供给用户切换,但是产品要求使用浏览器回退时也要让界面回退,对于浏览器来说,页面没有历史,所以不会改变,所以我们要手动添加来达到效果

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;//清除监听
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值