反应|如何检测页面刷新(F5) [英] React | How to detect Page Refresh (F5)

查看:321
本文介绍了反应|如何检测页面刷新(F5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我试过 stackoverflow post 使用javascript函数

I tried with stackoverflow post by using javascript functions

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

I used javascript function beforeunload still no luck.

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

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

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

这里我有关于 stackblitz 的完整代码

here I have full code on stackblitz

推荐答案

将其置于构造函数中:

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

它会起作用,请参阅 stackblitz

这篇关于反应|如何检测页面刷新(F5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆