react-native FlatList 的 onEndReached 频繁调用

版权声明:原创文章,未经允许不得转载!!! https://blog.csdn.net/halo1416/article/details/81512053

问题描述:今天写一个列表页面,需要写一个底部加载更多(分页)功能,使用了react-native的FlatList组件;并用FlatList的onEndReached方法来写分页。但是,onEndReached方法在render的时候就开始自动调用并且一直调用,一直调用到最后一页。代码如下:

原因查找:

自己找了好久,都不知道原因。百度了,有人说是其父组件高度不明造成的(这可能是某一些onEndReached频繁调用的原因,我也遇到过),但是也不行。最后,在一个大佬的博客中找到了答案:

把 onEndReached={this._onEndReached()}

改为 onEndReached={()=>this._onEndReached()}   就好了

改为 onEndReached={this._onEndReached.bind(this, 0, pageNumber+1)}  也可以

原因大概是:如果不加 '()=>' 或使用 bind(this) ,onEndReached就会把你当成每次都需要执行的一个方法,就会导致频繁调用。

感谢大佬!!

最后,上一下写的FlatList代码:

<FlatList
                        data={doingData}
                        keyExtractor = {(item, index) => index.toString()}       //不重复的key
                        refreshing={false}
                        renderItem={this._renderItem}
                        onEndReachedThreshold={0.5}
                        onEndReached={this._onEndReached.bind(this, 0, pageNumber+1)}       //加载更多==>>必须使用bind或者箭头函数,否则onEndReached会调用错误
                        initialNumToRender={4}         //一开始渲染的元素个数
                    />

数据加载函数:

componentWillMount(){
        this.getTaskList(0,this.state.pageNumber);
    }

    async getTaskList(status,page){
        try{
            let data = await API.task.tasklist(status,page);     //请求数据,status为0:进行中任务;status为1:已完成任务;
            const {doingData} = this.state;

            const {totalPage, list} = data;
            const all_doingData = doingData.concat(list);
            this.setState({
                doingData : all_doingData,          //所有进行中任务数据
                allPage : totalPage,                //进行中任务总页数
            });
        }catch (err) {
            console.log('err',err);
        }
    }

    _onEndReached(taskStatus, page){
        const {allPage} = this.state;
        this.setState({pageNumber: page});      //记录下当前页

        if(page <= allPage){
            this.getTaskList(taskStatus, page);
        }
    }

参考博客:https://www.cnblogs.com/wangyuehome/p/7816867.html  ==>> 感谢这位大佬

                  https://blog.csdn.net/wangqiuwei07/article/details/80791549  ==>> 这篇文章里也有解决方法

                  http://www.php.cn/js-tutorial-389193.html

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出

对博客文章的参考,若原文章博主介意,请联系删除!请原谅

猜你喜欢

转载自blog.csdn.net/halo1416/article/details/81512053