小编典典

反应| 如何检测页面刷新(F5)

reactjs

我正在使用React js。我需要检测page refresh。当用户点击刷新图标或按F5时,我需要找出事件。

我使用javascript函数beforeunload仍然没有运气。

onUnload(event) { 
  alert('page Refreshed')
}

componentDidMount() {
  window.addEventListener("beforeunload", this.onUnload)
}

componentWillUnmount() {
   window.removeEventListener("beforeunload", this.onUnload)
}

这里我在stackblitz上有完整的代码


阅读 297

收藏
2020-07-22

共1个答案

小编典典

将其放在构造函数中:

if (window.performance) {
  if (performance.navigation.type == 1) {
    alert( "This page is reloaded" );
  } else {
    alert( "This page is not reloaded");
  }
}

它将起作用,请在stackblitz上查看此示例。

2020-07-22