如何理解当用户滚动到div的底部?



当用户滚动到div底部时,我正在尝试分页(运行API请求),尽管它多次调用相同的滚动,导致数百个API请求一个分页。

componentDidMount中,我有

document.addEventListener('scroll', this.trackScrolling);

trackScrolling = async () => {
const wrappedElement = document.getElementById('profileArea');
if (this.isBottom(wrappedElement)) {
await this.paginateProfiles();
}
};

isBottom:

isBottom(el : any) {
return el.getBoundingClientRect().bottom <= window.innerHeight;
}

我也会分享paginateProfiles:

async paginateProfiles() {
if (this.state.profilesPaginating) {
return;
}
await this.setState({
profilesPaginating: true
});
var component = this;
var page = this.state.profilesNextPage;
await axios.get(process.env.REACT_APP_API_URL + '/profiles?amount=8&page=' + page)
.then(async (response) => {
await component.setState({
profiles: this.state.profiles.concat(response.data),
profilesNextPage: this.state.profilesNextPage + 1,
profilesPaginating: false,
});
});
}

问题技术描述:这很难解释,也很难解释是什么原因造成的,但似乎在大约10页后,它会突然进入垃圾邮件模式,发送大约50个API请求,并在加载时卡住。如果我滚动到顶部,它们会在几秒钟后停止,不再制作。

说明

没有一个解决方案解释它们依赖于每次事件侦听器之后总是变化的窗口高度。如果你的API没有返回任何结果(也许它已经用完了),事件处理程序将认为它仍然是初始在底部,因为它没有改变,事件侦听器已经被重新注册,因为概要文件已经被获取,但没有返回。

<<p>

解决方案/strong>比较结果长度,只有当它为!=时才添加事件侦听器(上次分页上有新记录,因此可能有更多)。

不理想,因为即使一个API请求没有返回任何内容,它也会使事件侦听器丢失,但它可以工作…

最新更新