我想用交集观察器API实现动态分页,它按预期工作:向下滚动页面,获取新数据,但之后页面滚动到其开头.我知道发生这种情况是因为Reaction在加载新信息后重新呈现页面.但我能以某种方式阻止这一切吗?
以下是我的代码:
function AllUniversititesList() {
const [loading, setLoading] = useState(false);
const [listOfUnis, setListOfUnis] = useState([]);
const [isSearched, setSearched] = useState(false);
const lastElement = useRef();
const observer = useRef();
async function fetchAllUnis() {
setLoading(true);
const result = await SearchService.getAllUniversities(); //return of data from API
setListOfUnis([...listOfUnis, ...result]);
setLoading(false);
}
useEffect(() => {
if(!listOfUnis.length) {
fetchAllUnis();
}
}, [])
useEffect(() => {
if(loading) return;
if(observer.current) observer.current.disconnect();
const callback = (entries, observer) => {
if(entries[0].isIntersecting) {
fetchAllUnis()
}
}
observer.current = new IntersectionObserver(callback);
observer.current.observe(lastElement.current);
}, [loading])
return (
<section className='min-h-screen bg-slate-200 pt-[7%] '>
{!loading && listOfUnis && listOfUnis.length > 0 && <UniversitiesList info = {listOfUnis}/>}
<div className='w-full h-4' ref={lastElement}></div>
</section>
)
}