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

如何在Ant Design Grid中无索引渲染服务器返回的布局化数据

Ant Design Grid 布局无索引实现方案

需求说明

使用Ant Design Grid组件实现布局,从服务器获取的数据条数不固定:

  • 前3条按指定规则展示:第一条Col占16列,第二条、第三条Col各占8列
  • 超过3条的数据默认隐藏,点击按钮后展示
  • 要求在map()中不使用索引实现上述逻辑

尝试代码(依赖索引)

dataSale.slice(0,maxCount).map(({...item},index)=>(
    (index===0)?(
        <Col key = {index}  span={16}>
            <SaleCard {...item}/>
        </Col>
        ):(
            <Col key={index} span={8}>
                <SaleCard {...item}/>
            </Col>
    )
))

无索引实现方案

通过解构拆分数据的方式避开索引判断,同时用数据自身的唯一标识作为key:

import { useState } from 'react';
import { Row, Col, Button } from 'antd';

const SaleLayout = ({ dataSale }) => {
  // 解构拆分数据:第一条、第二条、第三条,剩余为更多数据
  const [firstItem, ...remainingItems] = dataSale;
  const [secondItem, thirdItem, ...moreItems] = remainingItems;
  
  // 控制更多数据的显示/隐藏
  const [showMore, setShowMore] = useState(false);

  return (
    <>
      {/* 渲染前3条数据 */}
      <Row gutter={16}>
        {firstItem && (
          <Col span={16} key={firstItem.id}>
            <SaleCard {...firstItem} />
          </Col>
        )}
        {secondItem && (
          <Col span={8} key={secondItem.id}>
            <SaleCard {...secondItem} />
          </Col>
        )}
        {thirdItem && (
          <Col span={8} key={thirdItem.id}>
            <SaleCard {...thirdItem} />
          </Col>
        )}
      </Row>

      {/* 显示更多按钮(仅当有更多数据时展示) */}
      {moreItems.length > 0 && (
        <Button 
          type="link" 
          onClick={() => setShowMore(!showMore)}
          style={{ marginTop: 16 }}
        >
          {showMore ? '收起更多' : '查看更多'}
        </Button>
      )}

      {/* 渲染更多数据 */}
      {showMore && (
        <Row gutter={16} style={{ marginTop: 16 }}>
          {moreItems.map(item => (
            <Col span={8} key={item.id}>
              <SaleCard {...item} />
            </Col>
          ))}
        </Row>
      )}
    </>
  );
};

export default SaleLayout;

方案说明

  1. 数据拆分:通过ES6解构直接把前3条数据从数组中分离出来,不需要依赖索引判断位置
  2. key值优化:使用每条数据的唯一标识(如item.id)作为React元素的key,避免用索引带来的渲染问题
  3. 边界处理:用&&判断数据是否存在,兼容数据条数不足3条的场景
  4. 交互逻辑:通过状态控制更多数据的显示/隐藏,符合需求要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:31:15