关闭选项卡(React)时运行Firebase代码



当我的react应用程序的选项卡关闭或刷新时,我正在尝试运行一些firebase代码,到目前为止,firebase运行良好,但当我关闭选项卡时,代码不会执行。我认为这是因为firebase是异步的,因此选项卡在firebase代码执行完成之前关闭。有没有办法绕过这个问题,并确保我的firebase代码在选项卡关闭之前完成执行?

leaveLobby(e) {
e.preventDefault();
var firestore = firebase.firestore();
var docRef = firestore.doc("Games/Game " + this.state.Lobbycode);
docRef.get()
.then((docSnapshot) => {
if (docSnapshot.data().PlayerAmnt === 1) {
firestore.doc("Games/Active Games").update({
"Active Games" : firebase.firestore.FieldValue.arrayRemove(this.state.Lobbycode)
})
firestore.doc("Games/Game " + this.state.Lobbycode).delete();
} else {
docRef.update({
players : firebase.firestore.FieldValue.arrayRemove(this.state.name),
PlayerAmnt : firebase.firestore.FieldValue.increment(-1)
}) 
}
this.props.setInLobby(false, "", this.state.name);
})
return
}
componentDidMount() {
window.onbeforeunload = this.leaveLobby;
}

您可以挂接关闭事件

window.addEventListener("beforeunload", (ev) => 
{  
ev.preventDefault();
return ev.returnValue = 'Are you sure you want to close?';
});
componentDidMount: function() {
window.addEventListener('onbeforeunload', this.handleWindowClose);
},
componentWillUnmount: function() {
window.removeEventListener('onbeforeunload', this.handleWindowClose);
}

只需确保在构造函数的初始化过程中也将处理程序存储在本地字段中

  • this.handler = (ev) =>

然后根据需要使用以下

  • addEventListener("beforeunload", this.handler)
  • removeEventListener("beforeunload", this.handler)

最新更新