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

React中如何从对象数组生成多个独立动态表格?

问题:将对象内的多个数组分别渲染为独立表格

数据结构

我有一个包含两个键的对象,每个键对应一个对象数组,结构如下:

this.obj = {
      SCIENCE: [
        {
          assigned_to_name: 'James B',
          assigned_date: '11/12/2022',
          key: 0,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
        {
          assigned_to_name: 'Johny P',
          assigned_date: '11/13/2022',
          key: 2,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
      ],
      ARTS: [
        {
          assigned_to_name: 'Sara B',
          assigned_date: '11/13/2022',
          key: 0,
          id: 'VMCYN',
          code: 'ARTS#1',
          title: 'Arts group',
        },
      ],
    };

期望渲染效果

希望将每个数组分别渲染为独立的表格,示例样式如下:

SCIENCE对应的表格:

+-------+---------+--------+
| ID    | NAME    | CODE   |
+-------+---------+--------+
| Uto1O | James B | SCI#01 |
+-------+---------+--------+
| Uto1O | Johny P | SCI#01 |
+-------+---------+--------+

ARTS对应的表格:

+-------+---------+---------+
| ID    | NAME    | CODE    |
+-------+---------+---------+
| VMCYN | Sara B  | ARTS#1  |
+-------+---------+---------+

当前尝试的代码

import React from 'react';
import ReactTable from 'react-table';

export default class App extends React.Component {
  constructor() {
    super();
    this.obj = {
      SCIENCE: [
        {
          assigned_to_name: 'James B',
          assigned_date: '11/12/2022',
          key: 0,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
        {
          assigned_to_name: 'Johny P',
          assigned_date: '11/13/2022',
          key: 2,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
      ],
      ARTS: [
        {
          assigned_to_name: 'Sara B',
          assigned_date: '11/13/2022',
          key: 0,
          id: 'VMCYN',
          code: 'ARTS#1',
          title: 'Arts group',
        },
      ],
    };
  }

  render() {
    return (
      <div>
        {(() => {
          if (Object.keys(this.obj).length > 0) {
            for (const key of Object.keys(this.obj)) {
              const headings = ['id', 'code', 'assigned_to_name'];
              let value = this.obj[key];
              console.log('value', key, this.obj[key]);
              return (
                <table className="table">
                  <thead className="thead-dark">
                    <tr>
                      {headings.map((heading) => (
                        <th>{heading}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {value.map((row) => (
                      <tr>
                        {headings.map((heading) => (
                          <td>{row[heading]}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              );
            }
          }

          return null;
        })()}
      </div>
    );
  }
}

问题

当前代码仅能渲染出第一个表格(SCIENCE对应的表格),无法渲染ARTS的表格。

原因分析

在for循环内部使用了return语句,导致第一次循环执行时就直接返回了第一个表格的JSX,循环后续的迭代不会执行,因此只渲染了第一个表格。

解决方案

将for循环替换为map方法,遍历对象的键,返回一个包含所有表格的JSX数组。同时需要给每个表格元素添加唯一的key属性(使用对象的键作为key即可)。

修改后的render方法代码如下:

render() {
  const headings = ['id', 'code', 'assigned_to_name'];
  return (
    <div>
      {Object.keys(this.obj).length > 0 ? (
        Object.keys(this.obj).map(key => {
          const value = this.obj[key];
          return (
            <table key={key} className="table">
              <thead className="thead-dark">
                <tr>
                  {headings.map((heading) => (
                    <th key={heading}>{heading.toUpperCase()}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {value.map((row) => (
                  <tr key={row.key}>
                    {headings.map((heading) => (
                      <td key={`${row.key}-${heading}`}>{row[heading]}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          );
        })
      ) : null}
    </div>
  );
}

修改说明

  1. 移除了自执行函数,直接在JSX中进行条件判断和遍历
  2. 使用Object.keys(this.obj).map()替代for循环,遍历所有键并返回对应的表格数组
  3. 给每个表格、表头单元格、表格行和单元格添加了唯一的key属性,符合React列表渲染的要求
  4. 可选:将表头文本转为大写(heading.toUpperCase()),更贴近示例样式

这样修改后,就能渲染出两个独立的表格,分别对应SCIENCE和ARTS数组的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:21:01