react-native使用flatlist上拉加载下拉刷新

import React, {Component} from 'react'
import {View, Text, TouchableOpacity, FlatList, RefreshControl,ActivityIndicator} from 'react-native'
import * as Bituan from './components/Bituan'
import PublicLoad, {LoadingStatus} from "./components/PublicLoad"
import {apiPost} from "./api"


export default class Testflatlist extends Component {
constructor () {
super()
this.state = {
isRefreshing: false, //控制下拉刷新
isLoadMore: false, //控制上拉加载
page: 1, //当前请求的页数
totalCount: 0, //数据总条数
size: 10,
list: [],
loading: LoadingStatus.Show
}
}

async getList () {
console.log('>>生命周期渲染>>')
const {page, size, totalCount, list} = this.state || {}
const params = {page, size, site: '中文站', query: {nameTag: 'notice'}}
// {"site":"中文站","query":{"nameTag":"notice"},"page":1,"size":10}
const res = await apiPost('/v1/site/findArticlePageByNameTag', params).catch(err => {
Bituan.notice.show(err)
})
const {data} = res.data
console.log('>>>listData>>', params, res,data)
if (!data.success) {
this.setState({
loading: LoadingStatus.Hidden
})
Bituan.notice.show(data.error || data.message)
console.log('>>>listData>>', params, data)
}
if (page === 1) {
this.setState({
list: data.rows,
totalCount: data.count,
loading: LoadingStatus.Hidden,
isRefreshing: false
})
} else {
this.setState({
list: [...list, ...data.rows],
isLoadMore: false,
loading: LoadingStatus.Hidden
})
}
}

_onRefresh () {
console.log('>>下拉刷新>>')
this.setState({
isRefreshing: true,
page: 1
}, () => {
this.getList()
})
}
ItemSeparatorComponent(){
return(
<View style={{borderBottomColor:'green',borderBottomWidth:1}}></View>
)
}
_renderItem (item) {
console.log('>>item>>', item)
const {title} = item
return (
<View style={{height:50}}>
<Text style={{color:'#fff'}}>{title}</Text>
</View>
)
}

_onEndReached () {
console.log('>>上拉加载>>>')
const {page, size, isLoadMore, totalCount, list} = this.state || {}
if (list.length < totalCount && !isLoadMore) {
this.setState({
page: page + 1,
isLoadMore: true
}, () => {
this.getList()
})
}

}

ListFooterComponent () {
return (
<View>
<View style={{flexDirection:'row',color:'#fff',justifyContent:'center'}}>
<ActivityIndicator size="small" animating={true}/>
<Text style={{color:'#fff'}}>加载更多...</Text>
</View>
</View>
)
}

componentDidMount () {
this.getList()
}

render () {
const {list, isRefreshing, loading} = this.state || {}
return (
<PublicLoad loading={loading}>
<FlatList
keyExtractor={(item, index) => item.title+item.id}
data={list}
ItemSeparatorComponent={this.ItemSeparatorComponent}
onEndReachedThreshold={0.1}
ListFooterComponent={this.ListFooterComponent}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
colors={['#ff0000', '#00ff00', '#0000ff']}
tintColor={'#fff'}
progressBackgroundColor={"#ffffff"}
onRefresh={() => {
this._onRefresh()
}}
/>
}
onEndReached={() => this._onEndReached()}
renderItem={({item}) => this._renderItem(item)}></FlatList>
</PublicLoad>
)
}
}
posted @ 2020-07-10 14:31  lcosima  阅读(254)  评论(0编辑  收藏