首页 > 解决方案 > 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() 中添加事件侦听器,并且用户没有在窗口关闭时注销。

标签: javascriptreactjslocal-storage

解决方案


感谢评论,找到了使用 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'这样的事件


推荐阅读