簡體   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