Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Royalone94/fdc14bd6774a352483a11a419aa13278 to your computer and use it in GitHub Desktop.
Save Royalone94/fdc14bd6774a352483a11a419aa13278 to your computer and use it in GitHub Desktop.
A demo for react-native FlatList with load more action
class Demo extends React.Component {
state = {
data: [],
refreshing: true,
last_id: 0,
}
onEndReachedCalledDuringMomentum = true
componentDidMount() {
this._refreshData();
}
render() {
const { data } = this.state;
return (
<View style={styles.container}>
<FlatList
data={data}
keyExtractor={(_, index) => index.toString()}
renderItem={this._renderItem}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._refreshData}
/>
}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.1}
onMomentumScrollBegin={() => {
this.onEndReachedCalledDuringMomentum = false;
}}
/>
</View>
);
}
handleLoadMore = async () => {
if (!this.onEndReachedCalledDuringMomentum) {
try {
const { last_id, data } = this.state;
const res = await post('/api/demo', { last_id });
if (Array.isArray(res.data) && res.data.length === 0) {
return;
}
this.setState({
last_id: res.data.last_id,
data: data.concat(...res.data.list),
});
} catch(e) {
console.log(e);
}
this.onEndReachedCalledDuringMomentum = true;
}
}
_renderItem = ({item}) => {
return (
<Item
{...item}
onPress={() => this._prepareForDetail(item)}
/>
);
}
_refreshData = async () => {
this.setState({ refreshing: true, last_id: 0 });
try {
const res = await post('/api/demo', { last_id: 0 });
if (Array.isArray(res.data) && res.data.length === 0) {
this.setState({
data: [],
refreshing: false,
});
return;
}
this.setState({
refreshing: false,
data: res.data.list,
last_id: res.data.last_id,
});
} catch(e) {
this.setState({ refreshing: false });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment