You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-infinite-scroll-component中限制数据展示实现滚动加载?

解决react-infinite-scroll-component渲染全部数据的问题

你的代码存在三个核心问题,导致直接渲染了所有数据,修复步骤如下:


1. 数据源绑定错误

List组件直接绑定了原始完整数据源dataCard,而非用于控制分页的状态data,所以页面一加载就渲染了全部数据。

2. 数据追加逻辑错误

nextData函数里每次更新状态时,错误地把整个dataCard重新加入到现有数据中,不仅逻辑混乱,还会导致数据重复。正确的做法是从dataCard中截取未加载的片段,追加到现有数据里。

3. 滚动容器配置错误

InfiniteScroll的overflow设为inherit,容器不会出现滚动条,无法触发滚动加载的判断逻辑,需要改成auto或scroll。


修复后的完整代码

import { useState, useEffect } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { List, Row, Col, Divider } from 'antd';
import CardTrainingEvent from './CardTrainingEvent';

const AllTrainingEvent = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  // 假设dataCard是你的完整数据源(可替换为接口返回数据)
  // const dataCard = [...]; 

  // 初始化加载第一批数据
  useEffect(() => {
    const initialBatchSize = 2; // 首次加载数量,可按需调整
    setData(dataCard.slice(0, initialBatchSize));
  }, []);

  const nextData = () => {
    if (loading) return;
    setLoading(true);

    setTimeout(() => {
      const batchSize = 1; // 每次滚动加载的数量
      const startIndex = data.length;
      const endIndex = startIndex + batchSize;
      // 从完整数据源截取未加载的片段
      const newBatch = dataCard.slice(startIndex, endIndex);
      // 追加到现有数据中
      setData(prev => [...prev, ...newBatch]);
      setLoading(false);
    }, 1000);
  };

  return (
    <InfiniteScroll
      dataLength={data.length}
      // 动态判断是否还有更多数据:当前加载量小于总数据量
      hasMore={data.length < dataCard.length}
      next={nextData}
      loader={<h4 style={{ textAlign: "center" }}>Loading...</h4>}
      endMessage={
        <p style={{ textAlign: "center" }}>
          <Divider>Yay! You have seen it all</Divider>
        </p>
      }
      style={{
        maxHeight: 350,
        overflow: "auto", // 关键:让容器出现滚动条以触发加载
      }}
    >
      <List
        dataSource={data} // 改用分页状态data作为数据源
        renderItem={(item) => (
          <List.Item>
            <Row justify="space-between">
              <Col>
                <CardTrainingEvent {...item} />
              </Col>
            </Row>
          </List.Item>
        )}
      />
    </InfiniteScroll>
  );
};

export default AllTrainingEvent;

核心注意点

  • 始终用data状态作为List的数据源,dataCard仅作为完整数据仓库,不要直接绑定到组件
  • 每次加载新数据时,通过索引截取dataCard的片段,避免重复添加数据
  • 确保InfiniteScroll容器有明确的maxHeight和overflow: auto,这样滚动事件才能被组件捕获
  • hasMore的判断要和完整数据源的长度挂钩,不要写固定值,适配不同数据量场景

内容的提问来源于stack exchange,提问作者Dexy Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:24:20