![](/img/trans.png)
[英]Javascript / React Native — Event Listener only fires the first time
[英]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.