【问题标题】:React JS: Is beforeunload fired on page refresh?React JS:页面刷新时是否触发了 beforeunload?
【发布时间】:2020-07-04 06:34:52
【问题描述】:

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

【问题讨论】:

  • 为什么要在 componentDidMount() 中注册事件?你不能在componentWillUnmount里面注册吗? reactjs.org/docs/react-component.html#componentwillunmount
  • @Mohit 感谢您对此进行调查。我试过了,但是当窗口关闭时,unload() 方法似乎没有触发。当我重新打开窗口时,用户没有注销。
  • 这是beforeunload 事件的预期行为。 componentWillUnmount 将无法在窗口关闭时注册任何事件监听器。您可以查看herehere 以获得可能的解决方案
  • 考虑使用window.onbeforeunload
  • 使用ttl 设置本地存储变量。检查Load 上的ttl,然后您会发现页面刷新或窗口关闭并再次打开。普通人不能像刷新一样关闭/打开窗口,而是一个疯狂的?我不知道!:)

标签: javascript reactjs local-storage


【解决方案1】:

感谢 cmets,找到了使用 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)});
    }
}

getCookie() 来自https://www.w3schools.com/js/js_cookies.asp

如果窗口关闭,cookie 将不存在。不需要像'beforeunload'这样的事件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多