javascript - 阻止 popstate 事件运行?

标签 javascript reactjs react-router dom-events

我正在使用 React 和 React router,我希望这样当用户位于网站的某些部分时会出现一个确认框,告诉他们如果离开页面,他们可能会失去一些进度。目前,我有一个 onbeforeunload 事件来处理用户刷新或关闭窗口的时间,但是使用浏览器的后退按钮,我必须使用 onpopstate。使用下面所示的代码会显示确认框,但页面仍加载到之前的状态。

this.currentListener = function(event) {
  if (event.type === 'popstate') {
    event.preventDefault();
    event.stopPropagation();

    var leave =  confirm(message);
    console.log(leave)
  } else {
    return message;
  }
};
window.onbeforeunload = this.currentListener;
window.onhashchange = this.currentListener;

最佳答案

编辑:将组件转换为 mixin。根据 React 文档,多个生命周期调用将导致所有调用都被调用。 http://facebook.github.io/react/docs/reusable-components.html#mixins .

您是否考虑过在组件上使用静态 willTransitionFrom 方法?像这样的事情...

var PreventLeavingMixin = {
  statics: {
    willTransitionFrom: function(transition, component) {
      //you have access to your component's state and functions with the component param
      if (component.someMethod()) {
        //transition can make the navigation stop
        if (!confirm('Are you sure you want to leave?')) {
          transition.abort();
        }
      }
    }
  }
};

var MyComponent = React.createClass({
  mixins: [PreventLeavingMixin],
  render: function() {
    return: ...
  }
});

注意 - 您可能需要在 Router.create() 上指定 onAbort() 方法;

有关路由器转换的更多信息,请参见:http://rackt.github.io/react-router/#Route Handler

关于javascript - 阻止 popstate 事件运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586326/

相关文章:

javascript - 对象的方法可以作用于自身吗?

javascript - 将 DateTime 字符串转换为 javascript 中的时间戳

Javascript对象数组转字符串

reactjs - babel 冲突运行故事书

reactjs - 带有 TypeScript 的 React-router-dom

javascript - 无法读取 null 的属性 'getHostNode'

javascript - 将多边形 [x,y] 坐标数组转换为 SVG <path>

reactjs - 使用 {react-select} 时无法读取未定义的属性 'name'

reactjs - 如何为一个组件文件运行 Jest 覆盖

node.js - 如何在生产模式下使用 npm 代理(如 package.json 中的 proxy 参数)?