React Native踩坑之FlatList组件中的onEndReached

最近在做一个RN项目,有使用到FlatList这样一个RN封装的组件去做上拉加载更多功能,在iOS和Android平台上,总结了以下几个遇到的问题及解决方案

1. 进入页面onReached开始就被触发

解决方案:

// 伪代码如下
<FlatList 
      ...  
     onEndReachedThreshold={0.5}
      ...
/>

当onEndReachedThreshold设置大于1时,的确进入页面就触发,设置在0-1之间时按正常逻辑走

2. 上拉加载更多onReached被触发两次,造成重复请求资源,性能浪费

解决方案:

<FlatList
    ...
    onEndReached={() => {
	if (this.canLoadMore) {
		this.loadData(true); //
		this.canLoadMore = false;
	}
    }}
    onEndReachedThreshold={0.5}
    onMomentumScrollBegin={() => {
	this.canLoadMore = true; //初始化时调用onEndReached的loadMore
    }}
    ...
/>

这是一个官方的问题,在github上我们可以查到有人提了这个issue,目前一个解决方案就是我们可以通过设置一个flag去控制这个问题,当第一次触发完毕之后,将这个flag设置为false,避免重复去执行我们需要做的action操作

3. 通常情况下是先调用onMomentumScrollBegin,然后调用onEndReached,但是可能会存在意外情况

解决方案:

<FlatList
    ...
    onEndReached={() => {
	setTimeout(() => {
		if (this.canLoadMore) {
			this.loadData(true);
			this.canLoadMore = false;
		}
	}, 100)
    }}
    onEndReachedThreshold={0.5}
    onMomentumScrollBegin={() => {
	this.canLoadMore = true; //初始化时调用onEndReached的loadMore
    }}
    ...
/>
posted @ 2019-03-24 12:47  林璡  阅读(5576)  评论(0编辑  收藏  举报