在React的官方文档中提到 -
如果您熟悉React类生命周期方法,则可以将useEffect Hook视为componentDidMount,componentDidUpdate和componentWillUnmount的组合.
我的问题是 - 我们如何componentWillMount()在钩子中使用lifecyle方法?
我需要使用navigator.sendBeacon()窗口卸载,以便让我的服务器知道客户端已关闭他的窗口。我到处搜索过,但它对我不起作用。
作为参考,这篇文章中的解决方案也不起作用。
我有一个应用程序组件来包装我的整个项目。我试图在其componentDidMount()生命周期方法上设置卸载事件,但它不会触发。
componentDidMount() {
window.addEventListener("beforeunload", this.unload);
}
componentWillUnmount() {
window.addEventListener("beforeunload", this.unload);
}
unload(e) {
e.preventDefault();
e.returnValue = 'test';
navigator.sendBeacon(`http://localhost:8080/window-closed/${this.props.username}`);
return 'test';
}
Run Code Online (Sandbox Code Playgroud)
我希望服务器获得 AJAX 调用,并且窗口在关闭窗口之前提示用户“测试”。实际发生的情况是窗口像往常一样关闭。
注意:return 'test'&e.returnValue = ''语句纯粹用于测试。我只对 AJAX 请求感兴趣。
任何帮助将非常感激。