Created
October 26, 2019 05:49
-
-
Save FaiChou/1953bde392d7e33fb23430eaaecf4547 to your computer and use it in GitHub Desktop.
A demo for react-native FlatList with load more action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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