react-native 使用ScrollView实现下拉刷新上拉加载---直接复制

参考来自:https://blog.csdn.net/qq_39197547/article/details/87702205

官方写法:

const Item = ({ item, index, onPress ,  onPress2}) => {
    return (
        
            
                {
                    item.lesson_image_url===''?
                        
                            
                        
                        :
                        
                }

                
                    
                        {item.lesson_title}
                        {item.lesson_general===''?'暂无介绍':item.lesson_general}
                    
                    
                        {Util.toFixNum(item.virtual_num)} 人看过
                    
                
            
        
    );
}


let page = 1

class YHomeIndex extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing:false,
            curIndex:0,
            LessonsArr:[],
        };
    }

    getLessonIndex(curIndex) {
        console.warn('page=====',page)
        try {
            let datakey = [];
                 datakey[xxxx] = xxxxx;
                datakey[xxxx] = xxxxx;
                datakey['page'] = page;
                datakey['size'] = 10;  //获取数量
                let url = URLconstant.LESSON_LIST
                Util.get(url, datakey, (datas)=>{
                    console.log('列表',datas)
                    let data = datas.data.list
                    if(datas.status===0){
                        if(page === 1){
                            this.setState({
                                LessonsArr:data
                            })
                        }else{
                            Array.prototype.push.apply(this.state.LessonsArr, data);
                        }
                    }
                }, this.errorcallback.bind(this));
        } catch (e) {
            console.warn('请求失败===',e)
        }
    }


    //listview上拉触发
    async onEndReached() {
        let {curIndex} = this.state
        page +=1
        this.getLessonIndex(curIndex); // 数据请求函数  
    }

    onRefresh = () => {
        console.log('正在刷新')
        let {curIndex} = this.state
        page = 1
        this.getLessonIndex(curIndex)

        setTimeout(()=>{
            this.setState({
                refreshing:false
            })
        },2000)
    }

    jumpToClassDetail(){
            this.props.navigation.push('Y_ClassDetail')
    }

    render(){
        const renderItem = ({ item,index,separators }) => (
                  this.jumpToClassDetail(item)}/>   // 列表里的事件传入
                );
          return(
                
                        
                                        
                                            
                                        
                                    
                            }
                            // numColumns={1}  //以多少列展示
                            renderItem={renderItem}
                            refreshControl={
                                
                            }
                            keyExtractor={item => String(item.id)}
                            onEndReached={this.onEndReached.bind(this)}
                            // ListFooterComponent={this.renderFooter.bind(this)}
                        />
          
)}

export default YHomeIndex

// 按需

import React, {Component} from 'react';
import {
    Image,
    ScrollView,
    Text,
    TextInput,
    TouchableOpacity,
    View,
    StyleSheet,
    DeviceEventEmitter,
    ActivityIndicator,
    RefreshControl,
    StatusBar
} from "react-native";

let page = 1   //每次加载一页

export defaut class YHomeIndex extends Component {

    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loaded: false,
            curIndex:0,
            LessonsArr:[],

        };
    }

//事件、方法
//下拉刷新
    _onRefresh =()=>{
        this.setState({
            isRefreshing: true,
        });
        console.log('正在刷新')
        let user_id = this.state.user_id;
        page = 1   //刷新时自动取page为1的数据
        this.getHomeIndex(user_id);  //某个请求
        this.getLessonIndex(user_id,page);; //某个请求

        setTimeout(()=>{
            //.concat拼接字符串,数组
            this.setState({
                isRefreshing: false,
            })
        }, 2000);
    }

    //判断滚动到底部--上拉加载
    handleScrollEnd = (event) => {
        // console.log(event)
        const contentHeight = event.nativeEvent.contentSize.height;
        const scrollViewHeight = event.nativeEvent.layoutMeasurement.height;
        const scrollOffset = event.nativeEvent.contentOffset.y;
        console.log(scrollOffset + scrollViewHeight,"444444444444",contentHeight);
        const isEndReached = scrollOffset + scrollViewHeight+45 >= contentHeight; // 是否滑动到底部
        const isContentFillPage = contentHeight >= scrollViewHeight; // 内容高度是否大于列表高度

        if (isContentFillPage && isEndReached) {
            page+=1   //累加page
           // if(page>5){
           //     page = 5    //只给加载到第五页
           //}
            console.log('可以加载更多了','第',page,'页')
             let user_id = this.state.user_id;
            this.getLessonIndex(user_id,page);    //这就是上拉加载的请求,通过page = 1、page = 2...达到请求不同页的数据,最后将不同页的数据concat合并一起,实现了上拉加载 , 加载图片和图标可以自己在ScrollView下面定义
        }
    };



//数据请求
    getLessonIndex(user_id,curIndex,page) {
        try {
            //LOG("登录成功的user_id=====" + user_id);
            let datakey = [];
            if (user_id != null || user_id != '') {
                datakey['user_id'] = user_id;
                datakey['page'] = page;
                // datakey['alreadyOwn'] = 1;  //获取拥有的
                // console.log('curIndex=====',curIndex)
                if(curIndex===0){
                    datakey['order'] = 1;  //获取排序
                }
                datakey['size'] = 10;  //获取数量

                let url = URLconstant.LESSON_LIST
                Util.get(url, datakey, (datas)=>{
                    console.warn('课程列表-首页===',datas)
                    let data = datas.data.list
                    for(let item of data){
                        if(item.teacher.length === 0){
                            item.teacher = {teacher_name:''}
                        }
                    }
                    console.warn('课程列表-首页===(转teacher字段)',data)

                    if(datas.status===0){
                        if(page===1){   //刷新自动请求第一页内容
                            this.setState({
                                LessonsArr:data,
                                loaded:false,
                            })
                        }else {
                            let LessonsArr = this.state.LessonsArr   // 这里就是加载合并各个page的内容
                            console.log('合并前===LessonsArr', LessonsArr,)
                            let newLessonsArr = LessonsArr.concat(data)
                            console.log('合并后的LessonsArr===', LessonsArr)

                            this.setState({
                                LessonsArr: newLessonsArr
                            })
                        }
                    }
                }, this.errorcallback.bind(this));

            }
        } catch (e) {
            console.warn('请求失败===',e)
        }
    }


    errorcallback(){
        console.warn('请求失败2====')
    }





//组件

                            }
                            onScrollEndDrag={this.handleScrollEnd} //判断是否滚动到最底部
                        >


            
                {
                    this.state.LessonsArr.map((item,id)=>{
                          return(
                                  XXXXXX
                                )
                      })
                }


//这里自定义加载icon
}

你可能感兴趣的:(react-native 使用ScrollView实现下拉刷新上拉加载---直接复制)