首页 > 解决方案 > 如何在 reactjs 中的 Scroll 上从服务器加载更多内容

问题描述

我想调用 API 并使用滚动从数据库加载更多项目,最初,我只想显示五个记录,然后如果用户滚动并到达滚动底部,那么我想再显示五个记录。它即将延迟加载。请我是 reactjs 的新手,我该如何实现它。

这是我的代码。

{this.state.selected ==='text' && <div   style={{overflow:'auto', height:'200px'}}  data-tab-content="tab2">
                                                    {this.state.textList.length>0 ? this.state.textList.map(text=>
                                                   <p  >{text.text} </p>
                                                   ):<p>no record found</p>} */}

                                                   </div>}

我在这里制作

// get Text List
getTextList(){
    debugger
    fetch(baseUrl +`/language/listtext/${'1'}/${'5'}/${this.state.lesson_id}/${this.state.premiumprice_id}`)
    .then(response => response.json())

        .then(data => {
            debugger
          if(data.status ===200){
            debugger
            this.setState({
                textList: data.text.docs,
            })
          }else{
            this.setState({textList : []})
          }


        })
}

预先感谢

标签: reactjsscrolllazy-loading

解决方案


在 div 上添加 onScroll 事件,例如

// for example <div onScroll={this.handleScroll}/>
handleScroll = (e) => {
        const bottom = Number((e.target.scrollHeight - e.target.scrollTop).toFixed(0)) - e.target.clientHeight < 50;
        let page = this.state.page;
        if (bottom) {
            // write fetching logic here...
        }
    };

推荐阅读