之前在做一个业务的时候,后台返回的数据并没有做分页,而是一个数组直接吐出,如果数组的数据量不大还好,数据量一大对我们页面性能影响会比较大,处理的方式是用户滑动到底部的时候在自动加载更多。基于React主要实现如下。
首先监听页面的滚动事件
var that= document.querySelector('#container');
that.addEventListener('scroll' , function(){
var viewH = that.clientHeight
var contentH =that.scrollHeight,//内容高度
var scrollTop =that.scrollTop;
//距离底部还有100px时加载更多内容
if(contentH - viewH - scrollTop <= 100) {
this.getMoreItem()
}
}) 这里我们维护三个变量 一个是所有的数据allItem数组,一个是在页面展示的数据showItem,还有一个是我们当前的页码currentPage
//初始化的时候currentPage为0,我们假定一次只加载10条数据,那么可以这么写
componentDidMount(){
let currentPage = this.state.currentPage
for(let i = 0;i<10;i++){
showItem.push(allItem[i])
}
currentPage++
this.setState({
currentPage
})
}
render(){
return(
this.state.showItem.map(item=>{
<li key={key}>{item}</li>
})
)
}那当页面滑动到底部的时候,会触发getMoreItem()方法,这个方法的逻辑主要如下
getMoreItem(){
let currentPage = this.state.currentPage,
allItem = this.state.allItem,
showItem = this.state.showItem
//这边先做一个判断
if((currentPage+1)*10>=allItem.length){
this.setState({
showItem:allItem
})
}else{
for(let i = currentPage*10;i < (currentPage+1)*10;i++){
showItem.push(allItem[i])
}
currentPage++
this.setState({
showItem,
currentPage
})
}
}这样就可以实现我们的列表懒加载啦,图片懒加载实现思路也差不多

京公网安备 11010502036488号