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

查看:25
本文介绍了反应 |如何检测页面刷新 (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.

我使用 javascript 函数尝试了 stackoverflow post

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

推荐答案

将其放在构造函数中:

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

它会起作用,请在 stackblitz 上查看此示例.

It will work, please see this example on stackblitz.

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

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