【发布时间】:2019-06-19 23:26:49
【问题描述】:
当我阅读 ngFor 和 trackBy 的文档 (https://angular.io/api/common/NgForOf) 时,我想我明白 Angular 只会在 trackBy 函数返回的值发生变化时重做 DOM,但是当我使用它时在这里(https://stackblitz.com/edit/angular-playground-bveczb),我发现我其实一点也不明白。这是我的代码的基本部分:
export class AppComponent {
data = [
{ id: 1, text: 'one' },
{ id: 2, text: 'two' },
{ id: 3, text: 'three' },
];
toUpper() {
this.data.map(d => d.text = d.text.toUpperCase());
}
trackByIds (index: number, item: any) {
return item.id;
};
}
还有:
<div *ngFor="let d of data; trackBy: trackByIds">
{{ d.text }}
</div>
<button (click)=toUpper()>To Upper Case</button>
我期望单击按钮应该不将列表从小写更改为大写,但确实如此。我以为我在*ngFor 中对trackBy 使用了trackByIds 函数,并且由于trackByIds 只检查项目的id 属性,所以除了id 之外的任何内容的更改都不应该导致DOM要重做。我想我的理解是错误的。
【问题讨论】:
-
多次重读文档链接后,我认为 trackby 是“我应该在 DOM 中添加/删除/重新排序节点吗?”这个问题的答案。当数据发生更改时,我应该反映节点数据的更改。
-
tbh,在实践中,trackBy 与 ngFor 中组件的生命周期挂钩最相关。 trackby 函数将确定何时重新运行 init 系列挂钩,但更改检测仍始终根据选定的策略运行。渲染!= 变化检测。
标签: angular