本文介绍了当我们到达列表底部时,React Native FlatList 加载更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 React Native 的 FlatList 加载更多(非无限)
How to make load more with FlatList of React Native (Not infinite)
这是我的代码片段
<FlatList
data={this.props.data}
renderItem={({ item, separators }) => (
<TouchableHighlight
onPress={() => this._onPress(item)}
onShowUnderlay={separators.highlight}
onHideUnderlay={separators.unhighlight}
>
<Text> {item.title} </Text>
</TouchableHighlight>
)}
keyExtractor={item => item.id}
ListFooterComponent={this.renderFooter}
onEndReached={this.props.handleLoadMore}
onEndThreshold={0}
/>
还有我的 handleLoadMore
And my handleLoadMore
handleLoadMore = () => {
console.log("test"); // <---- this line run infinitely
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(filters)
})
.then(response => response.json())
.then(responseJson => {
this.setState({
itemData: [
...this.state.itemData,
...responseJson.estate_list
],
itemPage: this.state.itemPage + 1
});
})
.catch(error => {
console.error(error);
});
};
推荐答案
在 FlatList 中加载数据时出现问题,并且在重新渲染视图时将调用您的 onEndReached 处理程序.尝试设置这样的标志:
There is issue when loading data in FlatList and your onEndReached handler will be called when the view is re-rendered. Try setting a flag like this :
constructor(props){
super(props);
this.state = {
hasScrolled: false
}
}
然后添加这个方法:
onScroll = () => {
this.setState({hasScrolled: true})
}
将其连接到 FlatList:
Hook it up to FlatList:
<FlatList
onScroll={this.onScroll}
最终仅在滚动时加载:
handleLoadMore = () => {
if(!this.state.hasScrolled){ return null; }
//here load data from your backend
}
这篇关于当我们到达列表底部时,React Native FlatList 加载更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!