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

React中如何基于对象指定属性作为标题分组渲染数组数据

React实现按type字段分组渲染角色列表

核心实现逻辑

整个实现分两步走:

  • 对原始数组做分组转换:以type字段值为分组标识,把同类型的项归集到对应分组下
  • 遍历分组结果渲染:先渲染分组标题,再遍历当前分组下的所有成员,渲染对应的name和universe信息

完整代码示例

import React from 'react';

// 原始数据源
const characterList = [
  {
    name: "Thor",
    universe: "Marvel",
    type: "God"
  },
  {
    name: "Batman",
    universe: "DC",
    type: "Human"
  },
  {
    name: "Iron man",
    universe: "Marvel",
    type: "Human"
  },
];

export default function GroupedList() {
  // 用useMemo缓存分组结果,避免组件重渲染时重复做分组计算
  const groupedResult = React.useMemo(() => {
    // 用reduce做数组分组
    return characterList.reduce((groupMap, currentItem) => {
      const groupName = currentItem.type;
      // 分组不存在时初始化空数组
      if (!groupMap[groupName]) {
        groupMap[groupName] = [];
      }
      groupMap[groupName].push(currentItem);
      return groupMap;
    }, {});
  }, [characterList]);

  return (
    <div className="grouped-list">
      {/* 遍历所有分组 */}
      {Object.entries(groupedResult).map(([groupTitle, groupMembers]) => (
        <section key={groupTitle} style={{ marginBottom: 16 }}>
          {/* 分组标题,加粗展示 */}
          <h4 style={{ fontWeight: 'bold', margin: '0 0 8px 0' }}>
            {groupTitle}
          </h4>
          {/* 渲染组内所有成员信息 */}
          {groupMembers.map(member => (
            <div key={member.name} style={{ lineHeight: 1.5 }}>
              name: {member.name}&nbsp;&nbsp;&nbsp;universe: {member.universe}
            </div>
          ))}
        </section>
      ))}
    </div>
  );
}

补充说明

  • 如果数据是接口异步获取的,把characterList替换成存接口返回值的state变量即可,useMemo的依赖同步对应修改,数据更新时会自动重新生成分组结果
  • 列表遍历的key优先选数据唯一标识,示例里因为name唯一暂时用name做key,实际项目如果有id字段优先用id
  • 样式部分可以根据需求自行调整,上述代码渲染出来的结构和预期效果完全一致:

Human
name: Batman universe:DC
name: Iron man universe:Marvel

God
name: Thor universe: Marvel


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 04:27:21