繁体   English   中英

Angular OnPush+变化检测工作原理

[英]Principe of Angular OnPush + Change detection work

有 3 个组件:Parent、Child、ChildChild:

@Component({
  template: `<div>{{parentProp}}</div> <child-component></child-component>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent {
  public parentProp: string = 'parentValue1';

  constructor(){}

  ngOnInit() {
    setTimeout(() => this.parentProp = 'parentValue2', 2000)
  }
}

@Component({
  selector:'child-component',
  template: `<div>{{childProp}}</div> <child-child-component></child-child-component>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent {
  public childProp: string = 'childValue1';

  constructor(private cdr: ChangeDetectorRef){}

  ngOnInit() {
    setTimeout(() => {
        this.childProp = 'childValue2';
        thic.cdr.markForCheck();
    }, 10000);
  }
}

@Component({
  selector:'child-child-component',
  template: `<div>{{childChildProp}}</div>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent {
  public childChildProp: string = 'childChildValue1';

  constructor(){}

  ngOnInit() {
    setTimeout(() => this.childChildProp = 'childChildValue2', 3000);
  }
}

父->子->子子。 它们都是 OnPush。 在 parent 和 childChild 上没有 changeDetectorRef 和 setTimeout 3 秒,它们的模板属性正在更改。 在 Central - Child 上,10 秒后的 setTimeout 会更改其模板属性,而 changeDetectorRef 会执行 markForCheck()。 当它被执行时,子组件被标记为检查并重新渲染,它来到上面并执行父组件标记为检查。 完成 10 秒后,父组件重新渲染并显示其 prop 的更改值。 但正如我所知道的那样(从孩子到父母),然后它在下面(父母 - > 孩子 - > childChild)并且应该标记检查 childChild 组件。 但它没有。

接下来,如果我在 Child 中将 markForChecked() 更改为 detectChanges(),它应该重新渲染 Child(并且确实如此)及其子级(childChild)。 但是 childChild 不会重新渲染。

你能告诉我会发生什么吗?

markForCheck() 标记调用它的组件及其所有要检查的 OnPush 祖先。 即,如果在“child”中调用它,它将标记“child”和“parent”,而不是“childChild”。 变更检测周期尊重 ChangeDetectionStrategy,因此不会检查“childChild”

detectChanges() 检查调用它的组件和所有子组件,但再次尊重子组件的 ChangeDetectionStrategies。 这就是不检查“childChild”的原因。

暂无
暂无

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

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