RN使用FlatList实现上拉加载更多的代码

js 复制代码
import React, { useState, useEffect } from 'react';
import { FlatList, View, Text, ActivityIndicator, StyleSheet } from 'react-native';

const MyComponent = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  const fetchData = () => {
    setLoading(true);
    // 模拟从API获取数据
    setTimeout(() => {
      const newData = Array.from({ length: 10 }, (_, index) => ({ id: index + 1, text: `Item ${index + 1}` }));
      setData([...data, ...newData]);
      setLoading(false);
    }, 1000);
  };

  const handleLoadMore = () => {
    if (!loading) {
      setPage(page + 1);
      fetchData();
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const renderFooter = () => {
    return loading ? (
      <View style={styles.footer}>
        <ActivityIndicator size="large" color="blue" />
      </View>
    ) : null;
  };

  return (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <View style={styles.item}>
          <Text>{item.text}</Text>
        </View>
      )}
      keyExtractor={(item) => item.id.toString()}
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0.1}
      ListFooterComponent={renderFooter}
    />
  );
};

const styles = StyleSheet.create({
  item: {
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  footer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 20,
  },
});

export default MyComponent;
相关推荐
hkNaruto1 小时前
【AI】基于大模型的AI游戏地图生成、控制方案:AI Native Game Harness 迁移操作手册
前端·人工智能·游戏
IT_陈寒1 小时前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端
Acro1 小时前
快给macOS 上的Grok Bot换一套皮肤
前端
flash俊杰1 小时前
双引擎 OCR 编排:逐页判定、视觉优先、partial 语义与三层超时
前端
计算机魔术师1 小时前
Reddit 每周被 Google 偷走 100 万次点击,CEO 摊牌了
前端
前端繁华如梦1 小时前
用 React Three Fiber 做一栋能编辑的教学楼数字孪生
前端
前端繁华如梦1 小时前
用 React Three Fiber 做一套智慧医院数字孪生:编辑器、大屏和 BIM 浏览器
前端
俊昭喜喜里3 小时前
理解全局跨域CORS配置
前端
锋行天下6 小时前
DeepSeek写Langgraph就是个大傻逼,一本正经胡说八道
前端·人工智能·后端
jktantan6 小时前
每个节点 41 字节:把一棵百万节点树拆进 14 个 typed array
前端·javascript·vue.js·算法·typescript