【发布时间】:2023-02-17 00:16:20
【问题描述】:
为什么我的 useEffect 清理功能没有执行?
“已下载”在控制台打印,但“已清理”从不打印。
我需要在 useeffect 运行后(每次)调用它来清理内存。
这是我的代码:
useEffect(() => {
if (!downloadedFile) return;
const link = document.createElement("a");
link.href = downloadedFile.file;
link.setAttribute("download", downloadedFile.filename);
document.body.appendChild(link);
link.click();
console.log("downloaded");
return () => {
console.log("cleaned up");
link.remove();
window.URL.revokeObjectURL(downloadedFile.file);
dispatch(cleanUpAfterDownload());
};
}, [downloadedFile]);
提前致谢。
【问题讨论】:
-
当
downloadedFile发生变化时,清理功能将运行。你确定它正在改变吗? -
我假设它应该在下载记录后立即运行。我错了吗?
-
回答你,是的,下载的文件发生了变化,这就是打印下载日志的原因。我很困惑为什么“清理”之后没有很快被记录下来。
-
我仍然不知道为什么没有调用清理函数,但我将代码更改为:useEffect(() => { if (!downloadedFile) return; const link = document.createElement("a"); link.href = downloadedFile.file; link.setAttribute("下载", downloadedFile.filename); document.body.appendChild(链接); link.click(); console.log("下载"); link.remove() ; window.URL.revokeObjectURL(downloadedFile.file); dispatch(cleanUpAfterDownload()); }, [downloadedFile]);
标签: javascript reactjs react-hooks