【问题标题】:Why is my useeffect clean up function not executing?为什么我的 useEffect 清理功能没有执行?
【发布时间】: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


【解决方案1】:

下面的链接应该可以帮助你。您的状态在 useEffect 中发生变化,因此会出现意想不到的结果;

What is the expected return of `useEffect` used for?

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 2021-12-24
    • 2020-02-16
    • 2013-09-08
    • 2022-01-20
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多