1. 程式人生 > >下拉重新整理上拉載入

下拉重新整理上拉載入

import React, { Component } from "react";

import { withNavigation } from "react-navigation";

import RefreshListView, { RefreshState } from "react-native-refresh-list-view";

import { TouchableOpacity } from "react-native";

import Item from "./Item";

import { getData } from "./fetch";

class List extends Component {

constructor(props) {

super(props);

this.state = {

datas: [],

refershState: RefreshState.Idle, //預設重新整理狀態隱藏

page: 1, //預設顯示第一個頁

tab: props.tab,

limit: 10 //當前頁面線束10條資料

};

}

requestData = async () => {

let obj = {

page: this.state.page,

tab: this.state.tab,

limit: this.state.limit

}; //從狀態裡面取傳送給後臺的引數

let data = await getData("/topics", obj);

// console.error(data.data);

return data.data;

};

requestFirstData = () => {

try {

this.setState(

{

refershState: RefreshState.HeaderRefreshing,

page: 1

},

async () => {

let data = await this.requestData();//獲取新資料

this.setState({

datas: data,//用新資料覆蓋源資料

refershState: RefreshState.Idle

});

}

);

} catch (error) {

this.setState({

refershState: RefreshState.Failure

});

}

};

requestFootData = () => {

try {

this.setState(

{

refershState: RefreshState.FooterRefreshing,

page: this.state.page + 1//顯示第二頁

},

async () => {

let data = await this.requestData();

this.setState({

datas: [...this.state.datas, ...data],//增加資料

refershState:

this.state.datas.length > 30//判斷長度

? RefreshState.NoMoreData

: RefreshState.Idle

});

}

);

} catch (error) {

this.setState({

refershState: RefreshState.Failure

});

// console.error(error);

}

};

componentDidMount() {

this.requestFirstData();

}//初始化資料

onHeader = () => {

this.requestFirstData();

};

onFooter = () => {

this.requestFootData();

};

renderItem = rowData => {

return (

<TouchableOpacity

onPress={() =>

this.props.navigation.navigate("Detil", {

content: rowData.item.content

})//點選跳轉

}

>

<Item item={rowData.item} />

</TouchableOpacity>

);

};

render() {

return (

<RefreshListView//列表重新整理

data={this.state.datas}

keyExtractor={item => item.id}

renderItem={this.renderItem}

refreshState={this.state.refershState}

onHeaderRefresh={this.onHeader}//下拉重新整理

onFooterRefresh={this.onFooter}//上拉載入

/>

);

}

}

export default withNavigation(List);//可跳轉