react-infinite-scroller组件滚动分页加载

邹高峻
2023-12-01
// 部分代码片段
import InfiniteScroll from 'react-infinite-scroller';
import {Scrollbars} from 'react-custom-scrollbars';

//初始的state的状态
this.state = {
	loading: true,
	hasMore: true,
	pageNum: 1,
	pageSize: 20,
	total: 0,
	data: [],
};

// 获取下一页信息
getMore = () => {
     if (this.state.total === this.state.data.length) {
         return;
     }
     this.setState({
         loading: true,
         pageNum: this.state.pageNum + 1
     }, () => {
         this.initData(); //请求数据接口
     });
 }
//组件调用
<Scrollbars id='list-scrollbars' style={{height: "calc(100vh - 260px)"}} autoHide >
	<InfiniteScroll
   	   className="list-contents"
       initialLoad={false}
       pageStart={0}
       loadMore={this.getMore.bind(this)}
       hasMore={!this.state.loading && this.state.hasMore}
       useWindow={false}
   	 >
      {this.renderItemList(data)} // Tip:内部元素不要加高度以及overflow:auto等属性!!!!
      {total === data.length && data.length > 4 ? <div className="end-text">所有数据已看完</div> : ""}
   </InfiniteScroll>
   {this.state.loading ? <div style={{position: 'relative', marginTop: 30}}><Loading/></div> : ""} // 滚动加载状态的loading状态
</Scrollbars>

效果说明:
分页取数据,一页20条为例,滚动完20条之后就加载下一页~

 类似资料: