beforeUnload 不调用

beforeUnload does not call

我有一个 React 应用程序,我想在用户离开会话时从数据库中删除该用户。我尝试使用 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})
                })
            }
        })

我也试过使用绑定但没有箭头函数,但没有用

在我重现问题时,我把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 在控制台中。然后我导航到另一个 url。我在控制台中看到 handler fired 片刻。这意味着事件处理程序已被触发。
但是你 运行 异步代码,所以我认为你的网络调用在卸载事件期间被取消了。 async await 也可能有帮助(我还没试过抱歉,我在我的 phone 上)

另外值得注意的是:
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example: