在React JS上的浏览器后退按钮事件上显示警报

时间:2019-05-03 09:03:05

标签: reactjs

我必须在React js的浏览器返回事件上显示警报。我尝试使用import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt numPoints = 20 nanFrequency = 3 xVec = np.arange(numPoints, dtype=float) yVec = xVec colorVec = np.linspace(0,1,numPoints) colorVec[range(0, numPoints, nanFrequency)] = np.NaN cmap = mpl.colors.LinearSegmentedColormap.from_list("Blue-Red-Colormap", ["b", "r"], numPoints) # --- fig, axes = plt.subplots(nrows=2, figsize=(8, 2*6)) # --- ax = axes[0] ax.scatter(xVec, yVec, c=colorVec, cmap=cmap) ax.set_xlim([0, 20]) ax.set_ylim([0, 20]) # --- ax = axes[1] colorVec[np.isnan(colorVec)] = 2.0 cax = ax.scatter(xVec, yVec, c=colorVec, cmap=cmap) cax.cmap.set_over('y') cax.set_clim(0, 1) ax.set_xlim([0, 20]) ax.set_ylim([0, 20]) # --- plt.show() ,但不确定在React页面中将代码放置在何处。我应该放置在任何生命周期挂钩中还是渲染中?我不确定。请帮帮我。

6 个答案:

答案 0 :(得分:1)

查看此链接How to Detect Browser Back Button event - Cross Browser

关键点:

document.onmouseover = function() {
    //User's mouse is inside the page.
    window.innerDocClick = true;
}

document.onmouseleave = function() {
    //User's mouse has left the page.
    window.innerDocClick = false;
}

window.onhashchange = function() {
    if (window.innerDocClick) {
        //Your own in-page mechanism triggered the hash change
    } else {
        //Browser back button was clicked
    }
}

这可防止将后退空间用于后退

 $(function(){
        /*
         * this swallows backspace keys on any non-input element.
         * stops backspace -> back
         */
        var rx = /INPUT|SELECT|TEXTAREA/i;

        $(document).bind("keydown keypress", function(e){
            if( e.which == 8 ){ // 8 == backspace
                if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                    e.preventDefault();
                }
            }
        });
    });

答案 1 :(得分:1)

我尝试了很多解决方案,但是对于我来说并没有找到有效的解决方法

componentDidMount() {
        window.addEventListener("beforeunload", this._confirm);
        window.history.pushState(null, "", window.location.href);
        window.onpopstate = this._backConfirm;
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", this._confirm);
        window.onpopstate = () => { }
    }

    _backConfirm = async () => {
        let event = window.confirm("Changes that you may not be saved.");
        if(event){
            window.history.pushState(null, "", window.location.href);
        }
    }

    _confirm = (e) => {
        var confirmationMessage = "\o/";
        e.returnValue = confirmationMessage;
        return confirmationMessage;
    }

答案 2 :(得分:0)

您可以尝试一下,

window.addEventListener('popstate', (event) => {
  alert("You message");
});

您可以根据需要将其放置在componentWillMount()componentDidMount()中。

Ref

答案 3 :(得分:0)

最后,我自己解决了。我用下面的代码给出了解释:

首先,将以下代码添加到componentDidUpdatecomponentWillMount钩子中:

window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);
window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);

之所以要两次推送它,是因为只有两次推送状态才会更新状态。这是Ref。上面的代码将在页面加载的历史记录中推送当前页面的URL。

因此,由于使用pushState方法处理了历史记录,因此当单击后退浏览器按钮时,将再次重新加载同一页面。

然后在pushState方法上方添加以下代码:

window.addEventListener('popstate', (event) => {
  if (event.state) {
    //do your code here
  }
 }, false);

现在,当点击浏览器后退按钮时,上面的监听器将被调用,由于我们更新了state的{​​{1}}方法,因此pushState将是真实的,您可以在其中做任何想做的事。

答案 4 :(得分:0)

我找到了这个解决方案,对我来说很好用。

constructor(props) {
    super(props);
    this.state = {
        onClickBackButton: false
    };
}
componentDidMount() {
   window.history.pushState(null, null, window.location.pathname);
   window.addEventListener('popstate', this.onClickBackButton);
}

onBackButtonEvent = (e) => {
    e.preventDefault();
    if (!this.onClickBackButton) {

        if (window.confirm("Do you want to go back without submitting details?")) {
            this.onClickBackButton= true;
            // your custom logic to page transition,like react-router-dom 
            history.push()
        } else {
            window.history.pushState(null, null, window.location.pathname);
            this.onClickBackButton= false;
        }
    }
}

componentWillUnmount = () => {
    window.removeEventListener('popstate', this.onClickBackButton);
}

lines unfortunately separate for each strain replicate

答案 5 :(得分:0)

如果您使用React钩子,则可以在后续步骤中使用useEffect钩子

import React, { useState, useEffect } from "react";

const [finishStatus, setfinishStatus] = useState(false);

const onBackButtonEvent = (e) => {
    e.preventDefault();
    if (!finishStatus) {
        if (window.confirm("Do you want to go back ?")) {
            setfinishStatus(true)
            // your logic
            props.history.push("/");
        } else {
            window.history.pushState(null, null, window.location.pathname);
            setfinishStatus(false)
        }
    }
}

  useEffect(() => {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', onBackButtonEvent);
    return () => {
      window.removeEventListener('popstate', onBackButtonEvent);  
    };
  }, []);