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

React+MUI循环返回列表异常:仅显示前两个元素即终止

React+MUI 列表卡片每行3个元素的修复方案

问题分析

你的代码存在几个关键错误,导致只渲染前两个元素且循环异常:

  • for循环增量错误:i+3不会修改循环变量i的值,循环会一直停在初始值;加上循环内直接return,只会执行一次循环就返回结果。
  • 循环内直接return:第一次循环就返回JSX,后续循环根本不会执行,自然只渲染第一组元素。
  • slice参数错误:slice(i-1, 3*i)的结束索引计算错误,会导致每次取的元素数量不符合预期。
  • key值错误:key={{index}}传递的是对象,React需要字符串或数字类型的key,应该用key={index}(或元素唯一ID)。

修复方案

方案1:修复手动分组逻辑

修正循环逻辑,收集所有分组的JSX后统一返回:

const testList = [/* 你的元素列表 */];

const ListInvoices = (props) => {
  const invoicesList = () => {
    const rows = [];
    // 从0开始遍历,每次步进3
    for (let i = 0; i < testList?.length; i += 3) {
      // 每次取当前索引到索引+3的元素(最多3个)
      const invList = testList.slice(i, i + 3);
      rows.push(
        <Grid container alignItems="center" justifyContent="center" key={i}>
          {invList.map((elt, index) => (
            <Grid item key={`invoice-${i}-${index}`}>
              <Card sx={{ m: 2 }}>
                {/* 卡片内容 */}
              </Card>
            </Grid>
          ))}
        </Grid>
      );
    }
    return rows;
  };

  return (
    <Box sx={{ backgroundColor: "#f6f6f6" }} pt={4} pb={4}>
      <Container maxWidth="lg">
        {invoicesList()}
      </Container>
    </Box>
  );
};

方案2:利用MUI Grid自动布局(更简洁)

MUI Grid本身支持响应式布局,设置每个item占4列(12/3=4),无需手动分组即可自动每行显示3个:

const testList = [/* 你的元素列表 */];

const ListInvoices = (props) => {
  return (
    <Box sx={{ backgroundColor: "#f6f6f6" }} pt={4} pb={4}>
      <Container maxWidth="lg">
        <Grid container alignItems="center" justifyContent="center" spacing={2}>
          {testList?.map((elt, index) => (
            <Grid item xs={12} sm={6} md={4} key={index}>
              <Card sx={{ m: 2 }}>
                {/* 卡片内容 */}
              </Card>
            </Grid>
          ))}
        </Grid>
      </Container>
    </Box>
  );
};

说明:xs={12}表示移动端每行1个,sm={6}平板每行2个,md={4}桌面每行3个,可根据需求调整;spacing控制元素间距,比手动加margin更规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:01:25