使用flatList做列表頁上拉加載等多功能,主要使用以下兩個屬性:
onEndReached:當(dāng)列表被滾動到距離內(nèi)容最底部不足onEndReachedThreshold的距離時調(diào)用乍炉。
onEndReachedThreshold:決定當(dāng)距離內(nèi)容最底部還有多遠(yuǎn)時觸發(fā)onEndReached回調(diào)殖妇。<font size=3 color=#D2691E>其值是表示百分比的數(shù)值霍衫。</font>
使用過程中遇到以下兩個問題:
問題一: flatList初始化數(shù)據(jù)時首次請求的數(shù)據(jù)較少器紧,flatList高度較小韧拒,多次觸發(fā)onEndReached問題伞租,直到請求的數(shù)據(jù)滿足onEndReachedThreshold的設(shè)置贞谓。
通過設(shè)置FlatList的配置無法解決此問題。
情況一: 多頁數(shù)據(jù)葵诈,設(shè)置每頁請求數(shù)據(jù)數(shù)量可以鋪滿整屏
情況二: 當(dāng)只有一頁且數(shù)量較少時裸弦,通過設(shè)置特殊字段祟同,退出onEndTouch回調(diào)。如下代碼所示:
_onEndReached = () => {
const {isENd} = this.props //isEnd 表示當(dāng)前是數(shù)據(jù)請求的最后一頁
if(isENd) return;
...
};
問題二: flatList上拉刷新觸發(fā)onEndTouch問題
解決方案: onScrollEndDrag 和 onMomentumScrollEnd 將標(biāo)志字段置為false理疙,退出onEndTouch回調(diào)晕城,僅允許onScrollBeginDrag 和 onMomentumScrollBegin 情況正常調(diào)用onEndTouch回調(diào)。如下代碼所示:
<FlatList
...
onEndReached={this._onEndReached}
onEndReachedThreshold={0.2}
onScrollBeginDrag={() => {
console.log('onScrollBeginDrag');
this.canAction = true;
}}
onScrollEndDrag={() => {
console.log('onScrollEndDrag');
this.canAction = false;
}}
onMomentumScrollBegin={() => {
console.log('onMomentumScrollBegin');
this.canAction = true;
}}
onMomentumScrollEnd={() => {
console.log('onMomentumScrollEnd');
this.canAction = false;
}}
/>
_onEndReached = () => {
console.log('_onEndReached');
if(!this.canAction) return;
...
};