写作时间:2020/4/17
React-Native版本:0.62
本案例实现了FlatList组件的上拉加载功能,数据源于知乎,URI有失效可能,但整个代码结构可以参考
import React, {Component} from 'react';
import {ActivityIndicator, StyleSheet, FlatList, View, Text, Alert} from 'react-native';
const URI = 'https://www.zhihu.com/api/v4/roundtables/poor-econ/selected_contents?limit=7&after_id=1497603620171'; //初次获取数据的路径
export default class App extends Component {
constructor() {
super();
this.state = {
data: [], //用于数据存储
next: null, //获取后续数据的路径
isNetError: false, //网络请求状态
};
}
componentDidMount() {
// 加载完成后获取数据
this._fetchData(URI);
}
_fetchData = uri => {
fetch(uri)
.then(response => response.json())
.then(responseJson => {
this.setState({
data: this.state.data.concat(responseJson.data),
// 如果存在后续数据,next会获得新的链接,否则为null
next: responseJson.paging.next,
});
})
.catch(error => {
this.setState({
isNetError: true,
});
});
};
render() {
if (this.state.data.length === 0) {
return this._renderLoadingView();
}
if (this.state.isNetError) {
Alert.alert('ERROR');
}
return this._renderData();
}
//加载等待页
_renderLoadingView = () => {
return (
<View style={styles.container}>
<ActivityIndicator animating={true} color="red" size="large" />
</View>
);
};
_renderData = () => {
return (
<FlatList
style={{flex: 1}}
data={this.state.data}
renderItem={({item}) => (
<View style={{height: 100}}>
<Text style={{fontSize: 20}}>{item.answer.question.title}</Text>
</View>
)}
keyExtractor={(item, index) => item.answer.id.toString()}
onEndReachedThreshold={0.3}
onEndReached={this._onEndReached}
ListFooterComponent={this._renderFooter}
/>
);
};
_onEndReached = () => {
if (this.state.next) {
this._fetchData(this.state.next);
}
};
_renderFooter = () => {
if (this.state.next) {
return (
<View style={styles.footer}>
<ActivityIndicator />
<Text>正在加载更多数据...</Text>
</View>
);
} else {
return (
<View style={{height: 30, alignItems: 'center', justifyContent: 'flex-start'}}>
<Text style={{color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5}}>没有更多数据了</Text>
</View>
);
}
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffffff',
},
footer: {
flexDirection: 'row',
height: 24,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 10,
},
});