ReactJs浏览器“后退”按钮

dhr*_*att 7 reactjs

我正在使用Reactjs。我想警告用户单击后退按钮。我所做的是

handleWindowClose = (ev) => {
  ev.preventDefault();
  return ev.returnValue = 'Leaving this page will loose data';
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
}

componentWillUnmount = () => {
    window.removeEventListener('beforeunload',this.handleWindowClose);
}
Run Code Online (Sandbox Code Playgroud)

但是,这与单击后退按钮不起作用。所以我尝试这样做

handleWindowClose = (ev) => {
        ev.preventDefault();
        return ev.returnValue = 'Leaving this page will loose data';        
}

onBackButtonEvent = (e) => {
    e.preventDefault();
    if(confirm("Do you want to loose this data")){
    window.history.go(0);
    }else {
    window.history.forward();
  }
}

componentDidMount = () => {
    window.addEventListener('beforeunload',this.handleWindowClose);     
    window.addEventListener('popstate',this.onBackButtonEvent);
}

componentWillUnmount = () => {
    window.removeEventListener('beforeunload',this.handleWindowClose);
    window.removeEventListener('popstate',this.onBackButtonEvent);
}
Run Code Online (Sandbox Code Playgroud)

我没有使用react-router。是否有更好的方法仅使用react.Also我希望窗口不使用history.forward()停留在该页面上,因为我将失去窗口状态。

小智 6

在 React 中处理后退按钮时,我遇到以下问题:

  1. 第一次没有调用第一个popstate事件
  2. 它在执行我的后退按钮自定义逻辑后被调用两次

为了解决问题1,我做了以下代码:

componentDidMount() {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', this.onBackButtonEvent);
}
Run Code Online (Sandbox Code Playgroud)

为了解决问题 2,我做了以下代码:

onBackButtonEvent = (e) => {
    e.preventDefault();

    if (!this.isBackButtonClicked) {
        if (window.confirm("Do you want to save your changes")) {
            this.isBackButtonClicked = true;
            // Your custom logic to page transition, like react-router-dom history.push()
        }
        else {
            window.history.pushState(null, null, window.location.pathname);
            this.isBackButtonClicked = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记添加this.isBackButtonClicked = false; 在构造函数中并取消取消事件。

componentWillUnmount = () => {
    window.removeEventListener('popstate', this.onBackButtonEvent);
}
Run Code Online (Sandbox Code Playgroud)


U r*_*u s 1

看起来这onbeforeunload就是您想要的:检查此相关问题,其中包含一个有用的演示

MDN 文档还包含一个有用的示例。


假设您有一些不想使用的充分理由react-router,我将概述执行此操作的 JavaScript 方法

您似乎捕获了错误的事件。您想要获取 URL 哈希值的任何更改,因此您应该使用onhashchange.

文档中的示例:

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;
Run Code Online (Sandbox Code Playgroud)

不过,react-router考虑到您正在使用 React 进行开发,我会尝试一下。在这种情况下,browserHistory将是你的朋友。