我正在使用 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/