簡體   English   中英

ngOnChanges 僅在第一次觸發

[英]ngOnChanges fires only for the first time

我從父組件中獲取@Input(),並使用 ngOnChanges 來捕捉變化。 但它只觸發一次。 它會更改當前值,但之前的值始終未定義。 這就是我正在做的事情:

myArray=[];
ngOnChanges(changes:SimpleChanges):void{
  console.log(changes);
  if(changes.myInput.currentValue != undefined && changes.myInput.currentValue != changes.myInput.previousValue){
    for(var i=0;i<this.changes.myInput.currentValue.length;i++){
    console.log("length is" , i);
    this.myArray.push(this.changes.myInput.currentValue);
    }
  }
}

在這里, console.log(changes)只出現一次。 盡管每次@Input()更改時,其中的值都會更改。 我的myInput.currentValue是一個數組,每次通過父級的@Input()將新的 object 推送到數組時,我都想做一些事情。 它不在 if 條件內 go ,我找不到長度。

我的 myInput.currentValue 是一個數組,每次通過父級的 @Input() 將新的 object 推送到數組時,我都想做一些事情。

這就是問題的原因。 輸入的值(因此,參考)在技術上沒有改變 - object 發生突變,但參考保持不變 - 變化檢測機制錯過了它。 所以不要做這樣的事情

myArray.push(newValue);

在父母中,改為

myArray = [...myArray, newValue];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM