我正在使用 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();
}
}
我将不胜感激任何解释。