import React from "react";
import { Text, View, Image } from "react-native";
import RefreshListView, { RefreshState } from "react-native-refresh-list-view";
export default class FetchExample extends React.Component {
constructor(props) {
super(props);
this.state = {
dataValue: [], //数据源
RefreshState: RefreshState.Idle, //静止状态
page: 1
};
}
componentDidMount() {
this.onHeaderRefresh();
}
onHeaderRefresh = () => {
//更新状态,下拉刷新
this.setState({
refreshState: RefreshState.HeaderRefreshing,
page: 1
});
//网络请求
fetch(
`https://cnodejs.org/api/v1/topics?page=${
this.state.page
}&tab=good&limit=10`
)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataValue: responseJson.data,
refreshState: RefreshState.Idle,
page: this.state.page
});
})
.catch(error => {
this.setState({
refreshState: RefreshState.Failure
});
console.warn(error);
});
};
//上拉加载更多
onFooterRefresh = () => {
//更新状态,上啦加载
this.setState({
refreshState: RefreshState.FooterRefreshing
});
//网络请求
fetch(
`https://cnodejs.org/api/v1/topics?page=${
this.state.page
}&tab=good&limit=10`
)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataValue: [...this.state.dataValue, ...responseJson.data], //合并数据
refreshState: RefreshState.Idle,
page: this.state.page + 1
});
})
.catch(error => {
this.setState({
refreshState: RefreshState.Failure
});
console.warn(error);
});
};
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<RefreshListView
data={this.state.dataValue}
keyExtractor={(item, index) => item.id}
renderItem={({ item }) => (
<View
style={{
borderColor: "red",
borderBottomWidth: 1,
padding: 10
}}
>
<Image
style={{ width: 80, height: 80, borderRadius: 40 }}
source={{ uri: item.author.avatar_url }}
/>
<Text
onPress={() =>
this.props.navigation.navigate("Xiang", {
abc: item.content
})
}
>
{item.title}
</Text>
</View>
)}
refreshState={this.state.refreshState}
onHeaderRefresh={this.onHeaderRefresh}
onFooterRefresh={this.onFooterRefresh}
/>
</View>
);
}
}