無限スクロール2編実現
9423 ワード
制限が使用されています.useCallbackを使用して制限関数を作成し、dependencyを追加し、dependencyに基づいて制限関数を再作成します.
関数をクリアして、過去の時点のスクロールイベントをクリアし、現在の時点のスクロールイベントを登録します.これにより、現在のレンダーポイントの状態値を制限関数で参照できます.
また、メモリを最適化するためにthrottleも使用できます.cancel()を使用して、イベントキューに登録されている制限関数から、過去の時点で登録されたすべての制限関数を削除します.実装コード
props.isNext:Reductsと通信して取得するデータのReduct Storeデータを保存する
props.isLoading:現在データ取得中であることを示す
props.callNext:Fire Storeにアクセスするために関数を呼び出す
認識底部スクロール
関数をクリアして、過去の時点のスクロールイベントをクリアし、現在の時点のスクロールイベントを登録します.これにより、現在のレンダーポイントの状態値を制限関数で参照できます.
また、メモリを最適化するためにthrottleも使用できます.cancel()を使用して、イベントキューに登録されている制限関数から、過去の時点で登録されたすべての制限関数を削除します.
import React,{Fragment,useEffect,useCallback,useRef} from 'react'
import _ from 'lodash';
import InfiniteSpinner from './InfiniteSpinner';
function InfinityScroll(props) {
const dependency = [props.children,props.callNext,props.isNext,props.isLoading];
const _throttle = _.throttle(()=>{
if(props.isLoading){
return
}
let scrollHeight= document.documentElement.scrollHeight;
let scrollTop = document.documentElement.scrollTop
let clientHeight = document.documentElement.clientHeight;
if(scrollHeight-scrollTop-clientHeight < 300){
props.callNext(); // 데이터 fetch로직
}
},1000);
const throttle = useCallback(_throttle,dependency);
useEffect(()=>{
if(props.isLoading){
return;
}
window.addEventListener('scroll', throttle);
return ()=> {
window.removeEventListener('scroll',throttle);
throttle.cancel();
}
},dependency);
return (
<Fragment>
{props.children}
{props.isNext ? <InfiniteSpinner/>:null }
</Fragment>
)
}
InfinityScroll.defaultProps = {
children:null,
callNext:()=>{},
isNext:null,
isLoading:false
}
export default InfinityScroll
私が上で使っている依存性は、Redex Storeのデータです.props.isNext:Reductsと通信して取得するデータのReduct Storeデータを保存する
props.isLoading:現在データ取得中であることを示す
props.callNext:Fire Storeにアクセスするために関数を呼び出す
認識
if(scrollHeight-scrollTop-clientHeight < 300){
props.callNext();
}
現在のスクロール画面からブラウザの下部までの距離は、Height-SrollTop-ClientHeightをスクロールして計算します.最下部のpxが300 px未満であれば、すでに底打ちしていると判断し、以下のデータの取得を要求する.Reference
この問題について(無限スクロール2編実現), 我々は、より多くの情報をここで見つけました https://velog.io/@sae1013/무한스크롤-구현하기-2편テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol