代码之家  ›  专栏  ›  技术社区  ›  Talha Awan

React如何知道组件已从DOM中删除?

  •  9
  • Talha Awan  · 技术社区  · 8 年前

    在下面 Adding Lifecycle Methods to a Class

    5) 如果从DOM中删除了时钟组件,React将调用componentWillUnmount()生命周期挂钩,从而停止计时器。

    componentDidMount 生命周期挂钩。

    但对于 componentWillUnmount 它只是说“ 曾经 “。似乎表明这是真正的DOM,而不是反应DOM。不妨使用javaScript/jQuery和 组件将卸载 应该开火。

    2 回复  |  直到 7 年前
        1
  •  8
  •   jpuntd    8 年前

    每次调用组件的渲染函数时,都会重新构建虚拟DOM。如果不再需要组件,则会将其从虚拟DOM中删除。

    reconciliation .

    正是由于这一和解进程,人们才作出反应 知道

    如果另一个脚本(Javascript或jQuery)导致从实际DOM中删除某个组件,React将永远不会注意到它,因此不会调用componentWillUnmount()生命周期挂钩。

        2
  •  5
  •   enapupe    8 年前

    这不是真的。如果您手动从DOM中删除组件,它将不会启动 componentWillUnmount

    // Unmount children that are no longer present.
    for (name in prevChildren) {
      if (
        prevChildren.hasOwnProperty(name) &&
        !(nextChildren && nextChildren.hasOwnProperty(name))
      ) {
        prevChild = prevChildren[name];
        removedNodes[name] = ReactReconciler.getHostNode(prevChild);
        ReactReconciler.unmountComponent(
          prevChild,
          false /* safely */,
          false /* skipLifecycle */,
        );
      }
    }
    

    https://github.com/facebook/react/blob/5c6a496d98b80d19d851c2ec3a56d760b7118a50/src/renderers/shared/stack/reconciler/ReactChildReconciler.js

    unmountComponent 然后会打电话 组件将卸载

    组件将卸载 通过打开devtools并移除一些 组件将卸载