繁体   English   中英

为什么 Angular 在以下简单代码中产生 3 而不是 1?

[英]Why does Angular produce 3 rather than 1 in the following simple code?

为什么以下代码中的 output 是 3 而不是 1?

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

   i: number =0;  

  get count(): number{
    this.i++;
    return this.i;
  }
}

app.component.html

<h1>{{count}}</h1>

在浏览器上呈现的 output 是3

这是因为TypeScript被编译成javascript,而在js中没有“getter”的概念——有对象有函数。

因此,您正在做的是在模板中使用 function。 由于 angular 不知道什么可以更改 function 返回的值,因此在影响组件的每个更改检测周期对其进行评估。 因此,在您的情况下 - 在您的应用程序完全呈现之前运行了 3 个更改检测周期。

警告是——不要使用函数来绑定模板中的值,除非你使用 OnPush 更改检测策略(即使你真的需要使用 function 并且意识到可能的“陷阱”,也要仔细考虑)。

在旁注中 - 使用具有影响返回值的副作用的吸气剂可能在任何语言中都是不可行的,但我认为这只是为了说明你的问题。

这是一个更大的问题,涉及 Angular 如何处理变化检测。

如果您按如下方式更新您的组件(指定 OnPush ChangeDetectionStrategy),那么您将看到预期值 1。

    import { Component, ChangeDetectionStrategy } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class AppComponent {
    
       i: number =0;  
    
      get count(): number{
        this.i++;
        return this.i;
      }
    }

您可以在 Angular 的文档中阅读有关此枚举和相关主题的更多信息:

Stackblitz 示例

这是因为 Angular 的变更检测机制。

执行多个更改检测循环,并为每个循环调用“count”属性的 getter。

由于“count”属性的 getter 包含递增属性“i”值的指令,因此该值将在每个更改检测周期递增。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM