鍍金池/ 問(wèn)答/HTML5  HTML/ react-native中下拉刷新和上滑刷新獲取不到數(shù)據(jù)?

react-native中下拉刷新和上滑刷新獲取不到數(shù)據(jù)?

這是首次加載出來(lái)的10條數(shù)據(jù),當(dāng)我上滑刷新或者下拉刷新時(shí)獲取不到后面剩余的數(shù)據(jù)
圖片描述
首次加載獲取的10條數(shù)據(jù)后,把page加一
圖片描述
這是所有數(shù)據(jù)
圖片描述
當(dāng)我嘗試下拉或上滑的時(shí)候在加載更多數(shù)據(jù)(_loadMoreData)這里打了個(gè)斷點(diǎn),結(jié)果發(fā)現(xiàn)this._hasMoreData是undefined, this.state.isLoadingData也報(bào)了個(gè)錯(cuò),
我在constructor()里定義了isLoadingData,但這里沒(méi)有獲取到為什么呀?而且我在
_hasMoreData()里判斷了如果獲得的數(shù)據(jù)長(zhǎng)度不等于接口里傳的數(shù)據(jù)的總長(zhǎng)度就說(shuō)明有數(shù)據(jù),
然后在_fetchMoreData()判斷了如果沒(méi)有數(shù)據(jù)或者this.state.isLoadingState是false不作任何處理,但是這里顯示是有數(shù)據(jù)的,_fetchMoreData()沒(méi)有往下執(zhí)行是為什么?
圖片描述

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

//外部定義一個(gè)存放加載數(shù)據(jù)所需的條件參數(shù),nextPage表示刷新加載數(shù)據(jù)的頁(yè)數(shù),
//items表示加載后的數(shù)據(jù)存放的位置,totalResult表示數(shù)據(jù)的總數(shù)
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([]),
            //是否加載數(shù)據(jù)(用在上滑修改該state加載數(shù)據(jù))
            isLoadingData: false,
            //下拉刷新
            isRefreshing: false
        }
    }

    componentDidMount(){
        this._fetchData(1)
    }

    //請(qǐng)求數(shù)據(jù)
    _fetchData(page) {
        const that = this

        //如果頁(yè)數(shù)不為零,則修改上滑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){
                        //創(chuàng)建一個(gè)新數(shù)組
                        let newItems = cacleResult.items.slice()

                        if(page !== 0){
                            //新數(shù)組存放加載之后的所有數(shù)據(jù)(這是上滑刷新的)
                            newItems = newItems.concat(data.data)
                            console.log(newItems.length)
                            cacleResult.nextPage += 1
                            console.log(cacleResult.nextPage)
                        }else{
                            //新數(shù)組存放加載之后的所有數(shù)據(jù)(這是下拉刷新的)
                            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);
        }
    }

    //判斷是否有更多數(shù)據(jù)
    _hasMoreData(){
        return cacleResult.items.length !== cacleResult.totalResult
    }

    //加載更多數(shù)據(jù)
    _fetchMoreData(){
        if(!this._hasMoreData || this.state.isLoadingData){
            return
        }
        const page = cacleResult.nextPage
        console.log(page)
        this._fetchData(page)
    }

    //渲染出每一條view數(shù)據(jù)
    _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}>點(diǎn)贊</Text>
                        </View>
                        <View style={styles.itemFooterBox}>
                            <Icon
                                name='ios-chatboxes-outline'
                                size={25}
                                style={styles.comment}
                            />
                            <Text style={styles.handlerComment}>評(píng)論</Text>
                        </View>
                    </View>
                </View>
            </TouchableHighlight>
        )
    }

    //判斷距離底部的距離
    _renderFooter(){
        if(!this._hasMoreData && cacleResult.totalResult !== 0){
            return(
                <View>
                    <Text style={styles.noHasMoreData}>沒(méi)有更多數(shù)據(jù)了...</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
回答
編輯回答
孤慣

已解決, 是this的指向問(wèn)題,應(yīng)該在constructor里綁定this,或者直接使用剪頭函數(shù)

2018年9月22日 09:15