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

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

问题描述

我最近收到控制台错误`

I recently got the console error `

错误:[ngRepeat:dupes] 不允许在转发器中重复.使用 'track by' 表达式指定唯一键...

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?

推荐答案

它有一个缺点

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.

看看这个示例

尝试更改名称,没有任何反应.按索引删除轨道,它有效.按 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天全站免登陆