【发布时间】:2017-05-04 16:03:05
【问题描述】:
我将 angular2-infinite-scroll 与 trackBy ng-for 函数结合使用。 我注意到非常奇怪的行为,我无法理解。 我将 console.log 语句放在我的 trackBy 函数中,我注意到当我滚动时,日志被执行了数百次。
这是我担心的事情,我找不到任何关于这种行为的信息。这是一个例子:
https://plnkr.co/edit/k3YduRtqyXd0TNoPXwiQ?p=preview
//our root app component
import {Component} from '@angular/core'
@Component({
selector: 'my-app',
styles: [`
.search-results {
height: 100%;
// overflow: scroll;
}
.title {
position: fixed;
top: 0;
left: 0;
background-color: rgba(0,0,0,.5);
color: white;
width: 100%;
}
.title small {
color: #eaeaea;
}
`],
template: `
<h1 class="title well">{{ title }} <small>items: {{sum}}</small></h1>
<div class="search-results"
infinite-scroll
[infiniteScrollDistance]="scrollDistance"
[infiniteScrollThrottle]="throttle"
(scrolled)="onScrollDown()">
<p *ngFor="let i of array; trackBy: test">
{{ i }}
</p>
</div>
`
})
export class AppComponent {
array = [];
sum = 100;
throttle = 300;
scrollDistance = 1;
title = 'Hello InfiniteScroll v0.2.8, Ng2 Final';
constructor() {
this.addItems(0, this.sum)
}
test(index, test){
console.log('test');
}
addItems(startIndex, endIndex) {
for (let i = 0; i < this.sum; ++i) {
this.array.push([i, ' ', this.generateWord()].join(''));
}
}
onScrollDown () {
console.log('scrolled!!');
// add another 20 items
const start = this.sum;
this.sum += 20;
this.addItems(start, this.sum);
}
generateWord() {
return chance.word();
}
}
我将不胜感激。
【问题讨论】:
-
你看
NgFor源代码了吗?在 for 循环语句中有NgDoCheck钩子,其中称为differ.diff(),其中称为DefaultIterableDiffer.check,最后称为trackByFn函数。每次更改检测运行期间都会调用NgDoCheck。 -
这是个好方向。那么为什么在我滚动时调用 NgDoCheck 。如果 angular2-infinite-scroll 对滚动进行如此多的检查,这是性能问题吗?
-
我调查了代码。似乎没有什么是令人惊讶的。我很惊讶当容器订阅滚动事件时会发生什么。看起来在一次滚动操作中触发了很多事件。