为什么将变更检测调用两次?

时间:2019-06-27 07:15:03

标签: angular angular-component-life-cycle

我有一个没有逻辑的简单测试组件。 我渲染这个组件。 为什么DoCheck挂钩被调用两次?

据我所知,每次更改检测都调用DoCheck。 但是没有变化。 我只是渲染组件,DoCheck已经被调用了两次。 也是ngAfterContentChecked和ngAfterViewChecked。

enter image description here

3 个答案:

答案 0 :(得分:1)

Angular Change Detection - How Does It Really Work?

  

... Angular始终运行两次更改检测,第二次是   检测此类情况。在生产模式下,更改检测为   只能运行一次

答案 1 :(得分:0)

原因已在角度生命周期文档https://angular.io/guide/lifecycle-hooks#docheck

中进行了描述

通常Use this method to detect a change that Angular overlooked.

大多数这些初始检查是由Angular在页面其他位置首次呈现无关数据引起的。仅仅将鼠标悬停到另一个中就会触发呼叫。相对而言,很少有电话能揭示出相关数据的实际变化。显然,我们的实现必须非常轻巧,否则用户体验会受到损害。

答案 2 :(得分:0)

  

ngDoCheck

每触发任何可触发更改检测的内容(例如,点击处理程序,http请求,路由更改等)时,就会触发此操作。该生命周期挂钩主要用于调试目的;

演示何时触发ngDoCheck。

您可以看到在检查父组件时,在子组件上调用了ngDoCheck。现在假设我们为B组件实现onPush策略。流量如何变化?让我们看看:

Checking A component:
  - update B input bindings
  - call NgDoCheck on the B component
  - update DOM interpolations for component A
 if (bindings changed) -> checking B component:
    - update C input bindings
    - call NgDoCheck on the C component
    - update DOM interpolations for component B

   Checking C component:
      - update DOM interpolations for component C