反应:仅在浏览器返回时如何发生警报模式

时间:2018-11-15 05:14:10

标签: javascript reactjs

我只尝试在浏览器返回时才发出警报<Modal />。但是当前会显示默认警报,并且每次我从该网站离开时都会发生警报。我该如何解决?

constructor(props) {
  super(props);

  this.onUnload = this.onUnload.bind(this);
}

onUnload(event) {
  console.log("alert");
  event.returnValue = "alert";
}

componentDidMount() {
  window.addEventListener("beforeunload", this.onUnload);
}

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.onUnload);
}

1 个答案:

答案 0 :(得分:0)

我不使用React,但是可以使用下面的代码。

history.pushState(null, null);
window.addEventListener('popstate', function(e) {
    alert('BF')
});