IntersectionObserver实现上拉加载
一、前言
最近写的比较多的移动端页面开发,分页加载比较多,于是对其进行了一些研究,找到了一个比较方便的方法。其中关键为IntersectionObserver
这一对象。没用过的兄弟可以点链接
。
二、实现
import React, { useEffect, useState, useRef } from "react";
const [curPage, setCurPage] = useState(1);
const loadingRef = useRef(null);///.....
useEffect(() => {
const io = new IntersectionObserver((entries) => {
if (entries[0]["isIntersecting"]) {
setCurPage((page) => {
if (page < totalPage) {
return page + 1;
} else {
return page;
}
});
}
});
io.observe(loadingRef.current);
return () => io.disconnect();
}, [totalPage]);
<div className={styles.attendanceList}>
{approveList.map((v, i) => {
return (
<div className={styles.detailAtt} key={i}>{...}</div>
);
})}
<div ref={loadingRef} style={{ height: '1px', backgroundColor: '#F5F7F8' }}></div>
</div>
大概实现方式如上代码,通过检测ref来更新当前页curPage来进行发起新的请求获取下一页,这比scroll也更加方便。