Javascript 无限卷轴只能工作一次

Javascript 无限卷轴只能工作一次,javascript,reactjs,infinite-scroll,Javascript,Reactjs,Infinite Scroll,我正在用React构建这个webapp,其中有一个包含帖子的页面。我试图手动实现无限滚动功能,它似乎只工作了一次 当我的窗口上有最后一个元素时,它会调用api来获取更多的帖子,但是当我更新状态并获取“new”last post时,它不会获取更多的帖子。我相信我真的很接近解决这个问题,但我需要你们的一些指导 提前谢谢 这是我的密码 this.props.getPosts(this.state.page); //for the first load of the page this.scro

我正在用React构建这个webapp,其中有一个包含帖子的页面。我试图手动实现无限滚动功能,它似乎只工作了一次

当我的窗口上有最后一个元素时,它会调用api来获取更多的帖子,但是当我更新状态并获取“new”last post时,它不会获取更多的帖子。我相信我真的很接近解决这个问题,但我需要你们的一些指导

提前谢谢

这是我的密码

 this.props.getPosts(this.state.page); //for the first load of the page 

 this.scrollListener = window.addEventListener('scroll', (e) => {
        this.handleScroll(e)
 })

handleScroll = (e) => {
        let loadMoreElement = document.querySelector('.postGrid > div:last-child');
        var rect = loadMoreElement.offsetTop + loadMoreElement.clientHeight;
        var pageOffset = window.pageYOffset + window.innerHeight + 200;
        if(pageOffset > rect && !finished && !this.state.loading) {
            this.loadMore()
            this.props.getPosts(this.state.page)
            if(!this.state.has_more){ //has_more it's been set by the API when you get to the last page
                finished = true
                console.log("done")
            }
        } else if (finished){
            console.log("done")
        }}

    loadMore = () => {
        this.setState((prevState) => ({
            page: prevState.page + 1,
            loading: true,
        }))}

loadMore
方法中,您正在将
loadMore
设置为true,但是再次调用
loadMore
的条件之一是
loading
是否为false(
!this.state.loading


如果使用本地数据,则需要在某个时间点(如果涉及api调用)将
加载
再次设置为false,或者跳过
加载:true
部分。

在更新状态时,我在Redux文件数据操作中将其设置为false。当状态更新时,当我在上一篇文章中看到时,似乎loadMore不再被调用(但handleScroll仍然有效)。我检查了它,因为我修改了console.log(e),它仍然在console中获取窗口