gpt4 book ai didi

javascript - 关闭选项卡时不调用useEffect清理函数

转载 作者:行者123 更新时间:2023-12-05 00:28:06 25 4
gpt4 key购买 nike

我有这个仅用于清洁的 useEffect:

  useEffect(() => {
return function cleanup() {
if (!room || !currentPortal) return;
leavePortal(
room,
currentPortal,
currentUserProfile && currentUserProfile.uid
? currentUserProfile.uid
: uniqueId
);
detachListener();
};
}, [isFirstLoad, currentUserProfile, currentPortal]);

我可以来回走动,它工作得很好,但如果选项卡关闭,什么也不做。这就是 useEffect 的工作原理吗?它没有检测到标签关闭吗?

最佳答案

useEffect默认情况下不会检测标签关闭。

但是,您可以自己实现:

useEffect(() => {
const cleanup = () => {
// do your cleanup
}

window.addEventListener('beforeunload', cleanup);

return () => {
window.removeEventListener('beforeunload', cleanup);
}
}, []);

关于javascript - 关闭选项卡时不调用useEffect清理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com