【发布时间】:2021-09-12 16:43:28
【问题描述】:
当用户滚动到 div 的底部时,我正在尝试分页(运行 API 请求),尽管它为同一个滚动多次调用此操作,导致一次分页产生数百个 API 请求。
在componentDidMount我有,
document.addEventListener('scroll', this.trackScrolling);
这是做什么的:
trackScrolling = async () => {
const wrappedElement = document.getElementById('profileArea');
if (this.isBottom(wrappedElement)) {
await this.paginateProfiles();
}
};
是底部:
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直到你有响应,应该很容易实现,就像添加一个布尔状态一样简单
-
我已经完成了上述操作,并且如果它的评估结果为真,则在最高范围内阻止该方法,这意味着它不能两次调用该方法,但这就是我的问题打算解决的问题.
-
另外,是的,我正在使用异步上下文,但我正在等待所有调用,所以它不应该在这里造成任何问题。
-
@sojin 我试试看效果如何,谢谢。
标签: javascript reactjs dom-events