RN实现上拉刷新下拉加载
第一步添加依赖
import React, { Component } from “react”;
import {
Platform,
StyleSheet,
Text,
Image,
ScrollView,
View
} from “react-native”;
import RefreshListView, { RefreshState } from “react-native-refresh-list-view”;
export default class Top1 extends Component {
constructor(props) {
super(props);
this.state = { data: [], page: 1, refreshState: RefreshState.Idle };
}
//生命周期
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=1
)
.then(response => response.json())
.then(responseJson => {
this.setState({
data: responseJson.data,
page: this.state.page + 1,
refreshState: RefreshState.Idle
});
})
.catch(error => {
console.log(error);
});
};
//下拉加载
onFooterRefresh = () => {
this.setState({ refreshState: RefreshState.HeaderRefreshing });
fetch(
https://cnodejs.org/api/v1/topics?page=${ this.state.page }&tab=good&limit=1
)
.then(response => response.json())
.then(responseJson => {
this.setState({
data: […this.state.data, …responseJson.data],
page: this.state.page + 1,
refreshState: RefreshState.Idle
});
})
.catch(error => {
console.log(error);
});
};
render() {
return (
<RefreshListView
data={this.state.data}
keyExtractor={(item, index) => {
index;
}}
renderItem={({ item }) => (
<View style={{ flexDirection: “row”, width: “100%”, height: 80 }}>
<Image
style={{ width: 60, height: 60, margin: 5 }}
source={{ uri: item.author.avatar_url }}
/>
<Text
style={{ fontSize: 18 }}
// onPress={() => {
// this.props.navigation.navigate(“Details”, {
// abc: item.content
// });
// }}
>
{item.title}
)}
refreshState={this.state.refreshState}
onHeaderRefresh={this.onHeaderRefresh}
onFooterRefresh={this.onFooterRefresh}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: “center”,
alignItems: “center”,
backgroundColor: “#F5FCFF”
}
});