如何在本机反应中延迟加载滚动视图中特定数量的项目? [英] How to lazy load with specific number of items in scrollview in react native?

查看:50
本文介绍了如何在本机反应中延迟加载滚动视图中特定数量的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个应用程序,其中屏幕包含来自某个 api 的新闻提要加载数据,该 api 加载了大约 100 个数据.我想对其进行分页,例如先加载 10 个数据然后滚动更多以获得更多数据等等.这也被称为无限滚动.

I am trying to develop an app where a screen contains news feed loading data from a certain api which loads around 100 of the data. I would like to paginate it like first load 10 data then scroll more to get more data and so on.Which is also referenced as infinite scrolling.

推荐答案

您应该使用以下示例在滚动视图或平面列表中进行分页.在此处粘贴您的 url(API) 并运行.

You should use below example for pagination in scrollview or flatlist. Paste your url(API) here and run.

import React, { Component } from "react"
import {
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
    FlatList,
    Platform,
    ActivityIndicator
} from "react-native"

class FlatlistPagination extends Component {
    constructor() {
        super()
        this.state = {
            loading: true,
            //Loading state used while loading the data for the first time
            serverData: [],
            //Data Source for the FlatList
            fetching_from_server: false
            //Loading state used while loading more data
        }
        this.offset = 1
        //Index of the offset to load from web API
    }
    componentDidMount() {
        fetch("http://aboutreact.com/demo/getpost.php?offset=" + this.offset)
            //Sending the currect offset with get request
            .then(response => response.json())
            .then(responseJson => {
                //Successful response from the API Call
                this.offset = this.offset + 1
                //After the response increasing the offset for the next API call.
                this.setState({
                    serverData: [...this.state.serverData, ...responseJson.results],
                    //adding the new data with old one available in Data Source of the List
                    loading: false
                    //updating the loading state to false
                })
            })
            .catch(error => {
                console.error(error)
            })
    }
    loadMoreData = () => {
        //On click of Load More button We will call the web API again
        this.setState({ fetching_from_server: true }, () => {
            fetch("http://aboutreact.com/demo/getpost.php?offset=" + this.offset)
                //Sending the currect offset with get request
                .then(response => response.json())
                .then(responseJson => {
                    //Successful response from the API Call
                    this.offset = this.offset + 1
                    //After the response increasing the offset for the next API call.
                    this.setState({
                        serverData: [...this.state.serverData, ...responseJson.results],
                        //adding the new data with old one available in Data Source of the List
                        fetching_from_server: false
                        //updating the loading state to false
                    })
                })
                .catch(error => {
                    console.error(error)
                })
        })
    };

    renderFooter() {
        return (
            //Footer View with Load More button
            <View style={styles.footer}>
                <TouchableOpacity
                    activeOpacity={0.9}
                    onPress={this.loadMoreData}
                    //On Click of button calling loadMoreData function to load more data
                    style={styles.loadMoreBtn}
                >
                    <Text style={styles.btnText}>Load More</Text>
                    {this.state.fetching_from_server ? (
                        <ActivityIndicator color="white" style={{ marginLeft: 8 }} />
                    ) : null}
                </TouchableOpacity>
            </View>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                {this.state.loading ? (
                    <ActivityIndicator size="large" />
                ) : (
                        <FlatList
                            style={{ width: "100%" }}
                            keyExtractor={(item, index) => index}
                            data={this.state.serverData}
                            renderItem={({ item, index }) => (
                                <View style={styles.item}>
                                    <Text style={styles.text}>
                                        {item.id}
                                        {"."}
                                        {item.title.toUpperCase()}
                                    </Text>
                                </View>
                            )}
                            ItemSeparatorComponent={() => <View style={styles.separator} />}
                            ListFooterComponent={this.renderFooter.bind(this)}
                        //Adding Load More button as footer component
                        />
                    )}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        paddingTop: 30
    },
    item: {
        padding: 10
    },
    separator: {
        height: 0.5,
        backgroundColor: "rgba(0,0,0,0.4)"
    },
    text: {
        fontSize: 15,
        color: "black"
    },
    footer: {
        padding: 10,
        justifyContent: "center",
        alignItems: "center",
        flexDirection: "row"
    },
    loadMoreBtn: {
        padding: 10,
        backgroundColor: "#800000",
        borderRadius: 4,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    btnText: {
        color: "white",
        fontSize: 15,
        textAlign: "center"
    }
})

export default FlatlistPagination

这篇关于如何在本机反应中延迟加载滚动视图中特定数量的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆