React | How to detect Page Refresh (F5)

后端 未结 4 1385
北海茫月
北海茫月 2020-12-03 10:57

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.

I tried with stackoverflow po

相关标签:
4条回答
  • 2020-12-03 11:09

    If you are using either REDUX or CONTEXT API then its quite easy. You can check the REDUX or CONTEXT state variables. When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again. 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.

    0 讨论(0)
  • 2020-12-03 11:16

    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.

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 11:19

    Unfortunately currently accepted answer cannot be more considered as acceptable since performance.navigation.type is deprecated

    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.

    0 讨论(0)
  • 2020-12-03 11:26

    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.

    0 讨论(0)
提交回复
热议问题