为什么关闭窗口时componentWillUnmount不触发?

One would think that componentWillUnmount() in react would trigger when closing the application. According to the docs, componentWillUnmount() is triggered when unmounting it or if it's relative component is being destroyed. Why doesn't closing the window or tab unmount the component?

评论
  • matque
    matque 回复

    React would do that if it could, but think about it: closing the browser window means discarding all of the HTML, CSS, and JS on the page. Even if it tapped into the onbeforeunload event, it would be a waste to go about unmounting every component when they are about to be discarded anyway, and it would slow down closing the page. There historically hasn't been a good way to run any code when the tab is closed.

    However, there is an experimental API called the Beacon API that attempts to solve this problem, in the case that you want to send data over the network when the browser is closed.

  • isit
    isit 回复

    The Mounting term refers to actions on the DOM.

    生命周期方法是自定义功能,可在组件的不同阶段执行。当创建组件并将其插入DOM(安装),更新组件以及从DOM卸载或删除组件时,可以使用一些方法。

    Closing the window/tab fires the browser onbeforeunload event:

    当窗口即将卸载其资源时,将触发这些事件。
    window.addEventListener("beforeunload", function(event) { ... });
    window.onbeforeunload = function(event) { ... };