【发布时间】:2019-11-09 04:05:24
【问题描述】:
我有一个没有逻辑的简单测试组件。 我渲染这个组件。 为什么 DoCheck 钩子会被调用两次?
据我所知,每次检测更改都会调用 DoCheck。 但是没有变化。 我只是渲染组件并且 DoCheck 已经被调用了两次。 还有 ngAfterContentChecked 和 ngAfterViewChecked。
【问题讨论】:
标签: angular angular-component-life-cycle
我有一个没有逻辑的简单测试组件。 我渲染这个组件。 为什么 DoCheck 钩子会被调用两次?
据我所知,每次检测更改都会调用 DoCheck。 但是没有变化。 我只是渲染组件并且 DoCheck 已经被调用了两次。 还有 ngAfterContentChecked 和 ngAfterViewChecked。
【问题讨论】:
标签: angular angular-component-life-cycle
角度生命周期文档https://angular.io/guide/lifecycle-hooks#docheck已经描述了原因
通常Use this method to detect a change that Angular overlooked.
这些初始检查中的大多数是由 Angular 在页面其他位置首次渲染不相关数据时触发的。仅仅将鼠标移入另一个就会触发呼叫。相对较少的调用揭示了相关数据的实际变化。显然,我们的实现必须非常轻量级,否则用户体验会受到影响。
【讨论】:
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
【讨论】:
Angular Change Detection - How Does It Really Work?
... Angular 总是运行两次变更检测,第二次为 检测此类案件。在生产模式变化检测是 只运行一次
【讨论】: