//在util下新建List.js
import React, { Component } from "react";
import { FlatList, TouchableOpacity, Image, Text, View } from "react-native";
//导出列表
import { withNavigation } from "react-navigation";
//get和post
import { getData } from "../util/fetchData";
class List extends Component {
constructor(props) {
super(props);
this.state = {
refreshed: false, //默认不显示刷新图标
page: 1, //请求第几页
tab: this.props.tab, //类别
limit: 10, //每页请求的数量
data: [] //后台获取的数据
};
}
//网络请求第一次进来自动刷新数据
componentDidMount() {
this.requestFirstPage();
}
requestData = async () => {
//调用get方法
let res = await getData("/topics", {
page: this.state.page,
tab: this.state.tab,
limit: this.state.limit
});
return res;
};
requestFirstPage = () => {
//重置为第一页之后,在请求数据
this.setState(
{
page: 1,
refreshed: true
},
//回调函数
async () => {
let res = await this.requestData();
this.setState({
data: res.data,
//图标消失
refreshed: false
});
}
);
};
requestNextPage = () => {
//请求下一页,page+1
this.setState(
{
page: this.state.page + 1
},
async () => {
let res = await this.requestData();
//合并以前的数据
this.setState({
data: [...this.state.data, ...res.data]
});
}
);
};
render() {
return (
<FlatList
data={this.state.data}
//条目
renderItem={({ item }) => {
return (
//点击事件
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate("Detail", {
item: JSON.stringify(item)
});
}}
>
<View style={{ flexDirection: "row", padding: 20 }}>
<Image
style={{
width: 52,
height: 52,
//圆角
borderRadius: 16
}}
source={{ uri: item.author.avatar_url }}
/>
<Text
style={{
padding: 20,
borderBottomWidth: 0.5,
borderBottomColor: "#00ff00",
flex: 9
}}
>
{item.title}
</Text>
</View>
</TouchableOpacity>
);
}}
//下标
keyExtractor={(item, index) => index.toString()}
//进度条可以显示圆圈
refreshing={this.state.refreshed}
onRefresh={this.requestFirstPage}
//请求下一页
onEndReached={this.requestNextPage}
onEndReachedThreshold={0.0001}
/>
);
}
}
export default withNavigation(List);
网友评论