ngFor 指令是否在每次突变时重新渲染整个数组? [英] Does ngFor directive re-render whole array on every mutation?

查看:34
本文介绍了ngFor 指令是否在每次突变时重新渲染整个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一组项目:

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;

推荐答案

没有 ,只有当数组本身被不同的数组实例替换时才重新渲染.

更新

感谢 Olivier Boisse(见评论)

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 示例

如果使用的 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 中演示的动画在这个问题的答案中我如何才能在 angular 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆