简体   繁体   English

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

[英]React | How to detect Page Refresh (F5)

I'm using React js .我正在使用React js I need to detect page refresh .我需要检测page refresh When user hits refresh icon or press F5, I need to find out the event.当用户点击刷新图标或按 F5 时,我需要找出事件。

I tried with stackoverflow post by using javascript functions我尝试使用 javascript 函数使用stackoverflow 帖子

I used javascript function beforeunload still 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的完整代码

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上查看这个示例。

If you're using React Hook, UseEffect you can put the below changes in your component.如果您使用 React Hook,UseEffect 您可以将以下更改放入您的组件中。 It worked for me它对我有用

useEffect(() => {
    window.addEventListener("beforeunload", alertUser);
    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };
  }, []);
  const alertUser = (e) => {
    e.preventDefault();
    e.returnValue = "";
  };

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);
}

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.最新的 API 是实验性 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.作为一种解决方法,我只能建议在 redux(或您使用的任何东西)存储中保存一些值以指示重新加载后的状态,并在第一次路由更改时更新它以指示路由更改不是因为刷新。

It is actually quite straightforward, this will add the default alert whenever you reload your page.这实际上非常简单,每当您重新加载页面时,这都会添加默认警报。

In this answer you will find:在这个答案中,您会发现:

  1. Default usage默认用法
  2. Alert with validation带有验证的警报

1. Default Usage 1. 默认用法

Functional Component功能组件

useEffect(() => {
    window.onbeforeunload = function() {
        return true;
    };

    return () => {
        window.onbeforeunload = null;
    };
}, []);

Class Component类组件

componentDidMount(){
    window.onbeforeunload = function() {
        return true;
    };
}

componentDidUnmount(){
    window.onbeforeunload = null;
}

2. Alert with validation 2. 带有验证的警报

You can put validation to only add alert whenever the condition is true .您可以将验证设置为仅在条件为true时添加警报。

Functional Component功能组件

useEffect(() => {
    if (condition) {
        window.onbeforeunload = function() {
            return true;
        };
    }

    return () => {
        window.onbeforeunload = null;
    };
}, [condition]);

Class Component类组件

componentDidMount(){
    if (condition) {
        window.onbeforeunload = function() {
            return true;
        };
    }
}

componentDidUnmount(){
    window.onbeforeunload = null;
}

If you are using either REDUX or CONTEXT API then its quite easy.如果您使用的是 REDUX 或 CONTEXT API,那么它很容易。 You can check the REDUX or CONTEXT state variables.您可以检查 REDUX 或 CONTEXT 状态变量。 When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again.当用户刷新页面时,它会重置 CONTEXT 或 REDUX 状态,您必须再次手动设置它们。 So if they are not set or equal to the initial value which you have given then you can assume that the page is refreshed.因此,如果它们未设置或等于您给出的初始值,那么您可以假设页面已刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM