ngFor指令会在每次突变时重新渲染整个数组吗? [英] Does ngFor directive re-render whole array on every mutation?
问题描述
假设我们有一系列物品:
Let's say we have an array of items:
items = [
{ title: 'item 1'},
{ title: 'item 2'},
/* ... */
];
有一个渲染此数组的模板:
And there is a template that renders this array:
<ul>
<li *ngFor="let item of items">{{item.title}}</li>
</ul>
如果我通过push
/splice
添加/删除项目,angular2会重新渲染整个数组吗?还是仅添加/删除相应项目的标记?如果它仅更新,那么突变状态是否有任何差异-我应该更喜欢推送/拼接而不是数组替换吗?换句话说,这两种方法在渲染性能方面是否等效:
Wll angular2 rerender the whole array if I add/remove items via push
/splice
or will it only add/remove the markup for the corresponding items? If it does updates only, then is there any difference in mutation stategies -- should I prefer push/splice over array replacing? In other words, are these two approaches equivalent in term of rendering performance:
/* 1: mutation */
this.items.push({ title: 'New Item' });
/* 2: replacement */
var newArray = this.items.slice();
newArray.push({ title: 'New Item' });
this.items = newArray;
推荐答案
否,仅当数组本身被其他数组实例替换时,它才会重新渲染.
更新
感谢OlivierBoissé(请参阅评论)
Thanks to Olivier Boissé (see comments)
即使传递了不同的数组实例,Angular也会识别它是否包含相同的项目实例并且即使在那时也不会重新渲染.
Even when a different array instance is passed, Angular recognizes if it contains the same item instances and doesn't rerender even then.
另请参阅以下> StackBlitz示例
See also this StackBlitz example
如果使用过的IterableDiffer
在开头或中间识别并添加或删除,则将在该位置插入/删除一个项目,而无需重新渲染所有其他项目.
If the used IterableDiffer
recognizes and addition or removal at the beginning or in the middle, then an item is inserted/removed at that place without re-rendering all other items.
在Plunkers中回答此问题的动画我如何在角2中设置* ngFor动画?也证明了这一点.实际上,这种动画是实现这种方式(除了常规优化之外)的驱动因素
The animations demonstrated in Plunkers in answers of this question How can I animate *ngFor in angular 2? also demonstrate that. In fact this kind of animation was a driving factor to get this implemented this way (in addition to general optimization)
这篇关于ngFor指令会在每次突变时重新渲染整个数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!