首页 > 解决方案 > beforeUnload 不调用

问题描述

我有一个反应应用程序,如果他离开会话,我想从数据库中删除用户。我尝试使用 onUnload 执行此操作,但它根本不调用该方法。部分相关代码:

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

onUnload = ev => { // the method that will be used for both add and remove event
        const db = firebase.firestore();
        db.collection('parties').doc(this.state.partyNum).get().then(res=>{
            const result = res.data();
            if(result.users.length===1){
                db.collection('parties').doc(this.state.partyNum).delete()
            }else{
                db.collection('parties').doc(this.state.partyNum).update({
                    users: firebase.firestore.FieldValue.arrayRemove(this.state.username)
                }).then(()=>{
                    this.setState({unconfirmed: false})
                })
            }
        })

我也尝试了绑定和没有箭头功能,但它没有用

标签: javascriptreactjsfirebaseonunload

解决方案


在我重现问题时,我将 console.log 放入onUnload其中并访问该页面

componentDidMount() {
    console.log('add')
    window.addEventListener("beforeunload", this.onUnload);
}
 
componentWillUnmount() {
    console.log('add')
    window.removeEventListener("beforeunload", this.onUnload);
}

onUnload = ev => { 
    console.log('handler fired')
}

当我访问该页面时,我确定add它在控制台中。然后我导航到另一个网址。我在控制台中看到handler fired了一会儿。这意味着事件处理程序被触发。
但是您运行异步代码,所以我认为您的网络调用在卸载事件期间被取消。也async await可能有帮助(对不起,我没试过,我在我的手机上)

还值得注意:
https ://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

当此事件返回(或将 returnValue 属性设置为)非 null 或 undefined 的值时,将提示用户确认页面卸载。在旧浏览器中,事件的返回值显示在此对话框中。从 Firefox 44、Chrome 51、Opera 38 和 Safari 9.1 开始,将显示不受网页控制的通用字符串,而不是返回的字符串。例如:


推荐阅读