阵列
postsArary
在构造函数中初始化并且从未更新:
getLastPost()
总是返回第四个帖子,而不是动态添加的最后一个帖子。因此
IntersectionObserver
更新的
getLastPost()
方法:
getLastPost() {
const allPosts = postsContainer.querySelectorAll('.post');
return allPosts[allPosts.length - 1];
}
这并不能完全解决问题。第三页仍然无法加载,因为
counter()
在前面调用
loadMorePosts()
hasNextPage
false
loadMorePosts()
仍然应该加载更多的帖子。
更新的回调:
bindLoadMoreObserver() {
if (this.postsContainer) {
this.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry && entry.isIntersecting) {
observer.unobserve(entry.target);
this.loadMorePosts();
this.counter();
if (this.hasNextPage) {
observer.observe(this.getLastPost());
}
}
});
});
this.observer.observe(this.getLastPost());
}
}