【问题标题】:Running Firebase code when closing tab (React)关闭选项卡时运行 Firebase 代码(React)
【发布时间】:2021-05-14 20:17:02
【问题描述】:

当我的 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;
}

【问题讨论】:

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

你可以挂钩关闭事件

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2012-08-08
    • 2021-08-19
    • 2020-11-25
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    相关资源
    最近更新 更多