【问题标题】:Why the angular binding run 4 times?为什么角度绑定运行 4 次?
【发布时间】:2021-11-24 03:05:51
【问题描述】:

app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;

  str = () => {
    console.log('123123');
  };
}

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<p>{{str()}}</p>

当我重新加载浏览器并检查日志时。角度重新记录 4 次。如果您知道为什么会这样,请告诉我。

链接堆栈闪电战:https://stackblitz.com/edit/angular-ivy-zqjr2d?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

标签: angular binding


【解决方案1】:

这是因为您在模板中调用了一个方法,而 Angular 不知道该方法可以返回什么,所以它必须在每个更改检测周期中调用它。在开发模式下,Angular 会执行两次更改检测,此外,当您加载组件时,它必须渲染模板然后检查它是否有更改。

加载模板 + 检查模板是否正确 = 2 个周期。

开发模式每个循环两次。所以它变成 2x2 = 4。

【讨论】:

    【解决方案2】:

    默认情况下,组件树将每隔几秒重新检查/渲染一次。
    这种行为是由于 Angular 评估 DOM 的方式造成的(查看Angular lifecycle)。

    一种改进方法是在Component 对象中使用ChangeDectionStrategyOnPush 选项,因为它只会在显式调用时检查一次。

    This article 也可以帮到你=)

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 2022-11-25
      • 2015-06-15
      • 2018-05-07
      • 2020-02-26
      • 2016-12-04
      • 2020-08-31
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多