javascript - React JS:页面刷新时是否触发了 beforeunload?
问题描述
我的 App.js 中有以下代码。我想要做的是在窗口关闭时注销用户。
componentDidMount() {
if(localStorage.getItem("currentUser") !== null)
{
let currentUser = localStorage.getItem("currentUser");
this.setState({currentUser:JSON.parse(currentUser)});
}
window.addEventListener("beforeunload", this.unload);
}
unload = (e) => {
console.log('unload...')
localStorage.clear();
}
关闭窗口时清除localStorage并注销用户,但是刷新页面时似乎发生了同样的情况(尽管未执行console.log)。我可以在页面刷新时停止触发 unload() 方法吗?关闭浏览器窗口时,是否有更好的注销方式(清除 localStorage)?sessionStorage 不是一个选项,因为它在选项卡关闭时被清除。谢谢。
编辑:正如 Mohit 指出的那样,我尝试在 componentWillUnmount() 中添加事件侦听器,并且用户没有在窗口关闭时注销。
解决方案
感谢评论,找到了使用 cookie 的解决方法。当用户登录时,添加一个cookie,
this.setState({currentUser:JSON.parse(localStorage.getItem("currentUser"))});
document.cookie = "userLoggedIn=true";
并修改 componentDidMount() 如下,
componentDidMount() {
var c = this.getCookie("userLoggedIn");
if(localStorage.getItem("currentUser") !== null && c == "true")
{
let currentUser = localStorage.getItem("currentUser");
this.setState({currentUser:JSON.parse(currentUser)});
}
}
来自https://www.w3schools.com/js/js_cookies.asp的 getCookie()
如果窗口关闭,cookie 将不存在。不需要像'beforeunload'这样的事件
推荐阅读
- ios - 自动续订:介绍性定价导致“此项目当前正在修改。请稍后再试。”
- java - 启动eclipse时出现以下错误
- javascript - Vue.js Fetch 抛出 404 和 api 响应
- python - SQLAlchemy - 使用 DateTime 列查询以按月/日/年过滤
- javascript - 如何编写一个函数,将句子中每个单词开头的所有辅音字符串转换为“r”,直到它变成元音?
- typescript - Typescript Map 而不是 { [key: string]: SomeInterface }
- arrays - 数组中的反转,我错了什么。请查看下面的数学/伪代码
- apache-spark - Spark SQL中如何表示当前行和当前行+1
- arrays - 为什么我的阵列在 Project Euler 期间打印了数百次?
- c# - 如何转换存储在字符串中的十六进制并将其拆分,并将其存储在字节数组中