[英]React infinite scroll component
我正在嘗試制作類似於 facebook 的應用程序。當我到達頁面底部時,我正在從 API 獲取更多數據。我正在使用 React 和 Redux。簡化代碼:
const detectBottomOfPage= () => {
if((window.innerHeight + window.scrollY) > document.body.scrollHeight) {
dispatch(bottomOfPage()); //increases scrollCount
}
};
useEffect(() => {
window.addEventListener('scroll', detectBottomOfPage);
}, []);
useEffect(() => {
dispatch(fetchMoreData(scrollCount));
},[scrollCount]);
當我向下滾動時它工作正常,並獲取數據。 (頁面高度增加)。 但是當我刷新頁面時,它多次檢測到頁面底部。 我試圖在刷新前刪除偵聽器(beforeunload 事件),但刷新后它無法正常工作。 任何解決方案?
與其與所有不同的滾動怪癖作斗爭,最明智的解決方案是限制觸發無限滾動的速度。
一種方法是通過一些 state 檢查來更新您的效果:
const [lastFetch, setLastFetch] = React.useState(0);
useEffect(() => {
const now = Math.floor(Date.now()/3000);
if (lastFetch < now) {
dispatch(fetchMoreData(scrollCount));
setLastFetch(now);
}
},[scrollCount]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.