何时不在AngularJS ng-repeat中使用“按$ index跟踪"? [英] When not to use 'track by $index' in an AngularJS ng-repeat?

查看:71
本文介绍了何时不在AngularJS ng-repeat中使用“按$ index跟踪"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近收到控制台错误`

I recently got the console error `

错误:[ngRepeat:dupes]不允许在转发器中重复.使用跟踪依据"表达式指定唯一键...

Error: [ngRepeat:dupes] duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys...

— AngularJS错误参考-ngRepeat:dupes

然后我使用了'track by $index',问题就解决了...

which I then used 'track by $index' and the issue was solved...

但是,这让我开始思考...您是否有理由不想在ng-repeat中使用track by $index?

But that got me thinking... is there a reason why you wouldn't want to use track by $index in an ng-repeat?

我已经阅读了诸如这个问题其他文章 ,但似乎几乎所有文章都只谈论使用'track by'的优点.

I've read SO questions like this one as well as other articles, but it seems like almost all of the articles only talk about the advantages of using 'track by'.

有人可以列出缺点并举例说明何时不想使用track by $index吗?

Can someone list the disadvantages and give an example of when you wouldn't want to use track by $index?

推荐答案

它具有 disadvantage

It has a disadvantage,

'track by' 表达式按数组中的索引进行跟踪.这意味着只要索引保持不变,angularjs就会认为它是同一对象.

'track by' expression tracks by index in the array. It means that as long as the index stays the same, angularjs thinks it's the same object.

因此,如果替换数组中的任何对象,angularjs认为它没有改变,因为数组中的索引仍然相同.因此,更改检测不会在您期望的时候触发.

So if you replace any object in the array, angularjs think it didn't change because the index in the array is still the same. Because of that the change detection wont trigger when you expect it would.

看看这个 example

尝试更改名称,没有任何反应. 按索引删除轨道,它可以工作. 按item.name添加曲目,它仍然有效.

Try to change the name, nothing happens. Remove track by index, it works. add track by item.name, it still works.

这篇关于何时不在AngularJS ng-repeat中使用“按$ index跟踪"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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