react-native中下拉刷新和上滑刷新获取不到数据?

这是首次加载出来的10条数据,当我上滑刷新或者下拉刷新时获取不到后面剩余的数据
图片描述
首次加载获取的10条数据后,把page加一
图片描述
这是所有数据
图片描述
当我尝试下拉或上滑的时候在加载更多数据(_loadMoreData)这里打了个断点,结果发现this._hasMoreData是undefined, this.state.isLoadingData也报了个错,
我在constructor()里定义了isLoadingData,但这里没有获取到为什么呀?而且我在
_hasMoreData()里判断了如果获得的数据长度不等于接口里传的数据的总长度就说明有数据,
然后在_fetchMoreData()判断了如果没有数据或者this.state.isLoadingState是false不作任何处理,但是这里显示是有数据的,_fetchMoreData()没有往下执行是为什么?
图片描述

import React, { Component } from 'react';
import {
    AppRegistry,
    TabBarIOS,
    ListView,
    TouchableHighlight,
    RefreshControl,
    Image,
    Dimensions,
    ActivityIndicator,
    StyleSheet,
    Text,
    View
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

import request from '../common/fetchMethod.js';
import Config from '../common/config.js';
 
const width = Dimensions.get('window').width

//外部定义一个存放加载数据所需的条件参数,nextPage表示刷新加载数据的页数,
//items表示加载后的数据存放的位置,totalResult表示数据的总数
const cacleResult = {
    nextPage: 1,
    items: [],
    totalResult: 0 
}

class ChatList extends Component{
    constructor(props){
        super(props)
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows([]),
            //是否加载数据(用在上滑修改该state加载数据)
            isLoadingData: false,
            //下拉刷新
            isRefreshing: false
        }
    }

    componentDidMount(){
        this._fetchData(1)
    }

    //请求数据
    _fetchData(page) {
        const that = this

        //如果页数不为零,则修改上滑isLoadingData的state为true;
        //否则就修改下拉刷新isRefreshing的state为true
        if(page !== 0){
            this.setState({
                isLoadingData: true
            })
        }else{
            this.setState({
                isRefreshing: true
            })
        } 
        try {
            //request.get('http://www.rapapi.org/mockjs/33254/api/list?accessToken=labike&page=10')
            request.get(Config.api.baseUrl + Config.api.list, {
                accessToken: 'labike',
                page: page
            })
                .then(data => {
                    console.log(data)
                    if(data.success){
                        //创建一个新数组
                        let newItems = cacleResult.items.slice()

                        if(page !== 0){
                            //新数组存放加载之后的所有数据(这是上滑刷新的)
                            newItems = newItems.concat(data.data)
                            console.log(newItems.length)
                            cacleResult.nextPage += 1
                            console.log(cacleResult.nextPage)
                        }else{
                            //新数组存放加载之后的所有数据(这是下拉刷新的)
                            newItems = data.data.concat(newItems)
                        }
                        //console.log('new items:', newItems)
                    
                        
                        //更新cancleResult的items
                        cacleResult.items = newItems
                        console.log(cacleResult.items.length)

                        //console.log(cacleResult.items)
                        cacleResult.totalResult = data.total
                        //console.log(cacleResult.totalResult)

                        setTimeout(() => {
                            if(page !== 0){
                                that.setState({
                                    isLoadingData: false,
                                    dataSource: this.state.dataSource.cloneWithRows(
                                        //console.log(cacleResult.items),
                                        cacleResult.items
                                    )
                                })
                            }else{
                                that.setState({
                                    isRefreshing: false,
                                    dataSource: this.state.dataSource.cloneWithRows(
                                        //console.log(cacleResult.items),
                                        cacleResult.items
                                    )
                                })
                            }
                        }, 500)
                    }
                })
                .catch(error => {
                    if(page !== 0){
                        this.setState({
                            isLoadingData: false
                        })
                    }else{
                        this.setState({
                            isRefreshing: false
                        })
                    }
                    console.error(error)
                })
        } catch(error) {
            console.error(error);
        }
    }

    //判断是否有更多数据
    _hasMoreData(){
        return cacleResult.items.length !== cacleResult.totalResult
    }

    //加载更多数据
    _fetchMoreData(){
        if(!this._hasMoreData || this.state.isLoadingData){
            return
        }
        const page = cacleResult.nextPage
        console.log(page)
        this._fetchData(page)
    }

    //渲染出每一条view数据
    _renderItem = (item, index) => {
        return(
            <TouchableHighlight>
                <View style={styles.item}>
                    <Text style={styles.title}>{item.title}</Text>
                    <Image
                        source={{uri: item.thumb}}
                        style={styles.img}
                    >
                        <Icon
                            name='ios-play'
                            size={25}
                            style={styles.play}
                        />
                    </Image>
                    <View style={styles.itemFooter}>
                        <View style={styles.itemFooterBox}>
                            <Icon
                                name='ios-heart-outline'
                                size={25}
                                style={styles.up}
                            />
                            <Text style={styles.handlerText}>点赞</Text>
                        </View>
                        <View style={styles.itemFooterBox}>
                            <Icon
                                name='ios-chatboxes-outline'
                                size={25}
                                style={styles.comment}
                            />
                            <Text style={styles.handlerComment}>评论</Text>
                        </View>
                    </View>
                </View>
            </TouchableHighlight>
        )
    }

    //判断距离底部的距离
    _renderFooter(){
        if(!this._hasMoreData && cacleResult.totalResult !== 0){
            return(
                <View>
                    <Text style={styles.noHasMoreData}>没有更多数据了...</Text>
                </View>
            )
        }
        // if(!this.state.isLoadingData){
        //     return <View style={styles.noHasMoreData} />
        // }

        return <ActivityIndicator style={[styles.centering, {height: 80}]} />
    }

    //下拉刷新
    _onRefresh(){
        if(!this._hasMoreData || this.state.isRefreshing){
            return
        }
        
        this._fetchData(0)
    }

    render(){
        return(
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.headerTitle}>Header</Text>
                </View>
                <ListView
                      dataSource={this.state.dataSource}
                      renderRow={this._renderItem}
                    renderFooter={this._renderFooter}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh}
                            tintColor="#ff0000"
                            title="Loading..."
                        />
                    }
                    onEndReached={this._fetchMoreData}
                    onEndReachedThreshold={20}
                    showsVerticalScrollIndicator={false}
                    enableEmptySections={true}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    header: {
        paddingTop: 25,
        paddingBottom: 15,
        backgroundColor: '#ee735c'
    },
    headerTitle: {
        color: '#fff',
        fontSize: 15,
        fontWeight: '600',
        textAlign: 'center'
    },
    item: {
        width: width,
        marginBottom: 10,
        backgroundColor: '#fff'
    },
    title: {
        padding: 10,
        fontSize: 18,
        color: '#333'
    },
    img: {
        width: width,
        height: width * 0.5,
        resizeMode: 'cover'
    },
    play: {
        position: 'absolute',
        bottom: 14,
        right: 14,
        width: 46,
        height: 46,
        paddingTop: 9,
        paddingLeft: 18,
        backgroundColor: 'transparent',
        borderColor: '#fff',
        borderWidth: 1,
        borderRadius: 23,
        color: '#ed7b66'
    },
    itemFooter: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: '#eee'
    },
    itemFooterBox: {
        padding: 10,
        flexDirection: 'row',
        width: width / 2 - 0.5,
        justifyContent: 'center',
        backgroundColor: '#fff'
    },
    handlerText: {
        color: '#333',
        paddingLeft: 12,
        fontSize: 18
    },
    up: {
        color: '#333',
        fontSize: 22
    },
    handlerComment: {
        color: '#333',
        fontSize: 18
    },
    noHasMoreData: {
        color: '#777',
        textAlign: 'center'
    }
})


export default ChatList
阅读 3k
1 个回答

已解决, 是this的指向问题,应该在constructor里绑定this,或者直接使用剪头函数

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题