Javascript 反应 | 如何检测页面刷新 (F5)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/50026028/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React | How to detect Page Refresh (F5)
提问by Maria Jeysingh Anbu
I'm using React js. I need to detect page refresh. When user hits refresh icon or press F5, I need to find out the event.
我正在使用React js。我需要检测page refresh. 当用户点击刷新图标或按 F5 时,我需要找出事件。
I tried with stackoverflow postby using javascript functions
我通过使用 javascript 函数尝试了stackoverflow 帖子
I used javascript function beforeunloadstill no luck.
我使用 javascript 函数beforeunload仍然没有运气。
onUnload(event) { 
  alert('page Refreshed')
}
componentDidMount() {
  window.addEventListener("beforeunload", this.onUnload)
}
componentWillUnmount() {
   window.removeEventListener("beforeunload", this.onUnload)
}
here I have full code on stackblitz
这里我有关于stackblitz 的完整代码
采纳答案by Abdellatif Derbel
Place this in the constructor:
把它放在构造函数中:
if (window.performance) {
  if (performance.navigation.type == 1) {
    alert( "This page is reloaded" );
  } else {
    alert( "This page is not reloaded");
  }
}
It will work, please see this example on stackblitz.
它将起作用,请在stackblitz上查看此示例。
回答by Rvach.Flyver
Unfortunately currently accepted answer cannot be more considered as acceptable since performance.navigation.type is deprecated
不幸的是,由于 performance.navigation.type 已被弃用,目前接受的答案不能被视为可以接受
The newest API for that is experimental ATM. As a workaround I can only suggest to save some value in redux (or whatever you use) store to indicate state after reload and on first route change update it to indicate that route was changed not because of refresh.
最新的 API 是实验性 ATM。作为一种解决方法,我只能建议在 redux(或您使用的任何东西)存储中保存一些值以指示重新加载后的状态,并在第一次路由更改时更新它以指示路由不是因为刷新而更改。
回答by Will
Your code seems to be working just fine, your alert won't work because you aren't stopping the refresh. If you console.log('hello')the output is shown.
您的代码似乎工作得很好,您的警报将不起作用,因为您没有停止刷新。如果您console.log('hello')显示输出。
UPDATE ---
更新 - -
This should stop the user refreshing but it depends on what you want to happen.
这应该会阻止用户刷新,但这取决于您想要发生的情况。
componentDidMount() {
    window.onbeforeunload = function() {
        this.onUnload();
        return "";
    }.bind(this);
}

