gpt4 book ai didi

javascript - Angular 4中不同变量的控制检测变化策略

转载 作者:行者123 更新时间:2023-11-30 14:48:28 27 4
gpt4 key购买 nike

我不是 Angular 4 的专家,我一直在使用 Angular 4 构建应用程序。因此,我试图了解变化检测功能,因为我不清楚。目前,我在 ngAfterViewInit 方法中使用 ChangeDetectorRef.detectChanges()。假设我有一个示例 UI 组件,它是这样的:

<div>{{state}}</div>

我在类中有两个变量,它们是 statestateUpdater。我的状态更新器:

this.state = 0;
setInterval(() => {
this.stateUpdater = 0;
if (this.stateUpdater % 8 === 0) {
this.state = this.stateUpdater;
}
this.stateUpdater++;
}, 100);

因此,对于这种情况,stateUpdater 将每 100 毫秒更新一次,而 state 将每 800 毫秒更新一次。我的问题是“detectChanges”函数将每 100 毫秒调用一次以更新 UI?否则,将每 800 毫秒调用一次?

如果每 100 毫秒调用一次,我该如何防止这种行为?因为这对于 UI 透视图来说是完全低效的。

我将不胜感激任何建议。谢谢。

最佳答案

生命周期适用于整个组件或指令。

触发变化检测的是划setInterval,不是变化的stateUpdater值。

如果某些代码段中不需要某些更改检测,可以通过使用 runOutsideAngular 评估超出当前区域的代码来在本地禁用它。 . run 可以在本地重新启用它:

ngZone.runOutsideAngular(() => {
setInterval(() => {
if (this.stateUpdater % 8 === 0) {
ngZone.run(() => {
// yes! change detection
this.state = this.stateUpdater;
});
}
// no change detection
this.stateUpdater++;
}, 100);
});

或者,可以在需要时手动触发更改检测:

zone.runOutsideAngular(() => {
setInterval(() => {
if (this.stateUpdater % 8 === 0) {
// yes! change detection
this.state = this.stateUpdater;
changeDetectorRef.detectChanges();
}
// no change detection
this.stateUpdater++;
}, 100);
});

可以使用 detach 暂时禁用更改检测并通过 reattach 启用。它们的影响不是局部的,整个组件都会受到影响:

  setInterval(() => {
if (this.stateUpdater % 8 === 0) {
changeDetectorRef.reattach();
// yes! change detection
this.state = this.stateUpdater;
} else {
// no change detection
changeDetectorRef.detach();
this.stateUpdater++;
}
}, 100);

变化检测是相对低成本的操作,这就是它存在的原因。如果在绑定(bind)到 View 的属性中未检测到任何更改,则不会更新 View 。

由于变更检测是框架的重要组成部分,它应该在大多数情况下按原样使用,而对其进行细粒度控制违背了使用框架的目的,并且可以被视为过早优化,除非另有证明。

为了不导致 View 更改的更改检测周期不会对性能造成重大影响, View 绑定(bind)不应该是昂贵的。

关于javascript - Angular 4中不同变量的控制检测变化策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48527384/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com