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

React开发:如何基于嵌套JSON的Events数据渲染React Table

React Table展示嵌套JSON中Events数组的解决方案

问题核心原因

  1. 你的JSON结构是外层数组包裹单个对象,真正需要的表格数据源是该对象下的Events数组,而非整个外层数组
  2. React Table默认不支持Events.Id这类嵌套点路径的accessor,当数据源直接使用Events数组的每一项时,直接用字段名即可

步骤1:修正列定义

将列的accessor改为对应字段名,因为后续数据源会是Events中的单个对象:

export const COLUMNS = [
  {
    header: 'Id',
    accessor: 'Id'
  },
  {
    header: 'Line',
    accessor: 'Line'
  },
  {
    header: 'Error',
    accessor: 'Error'
  }
]

步骤2:修正组件数据源提取

从JSON中正确提取Events数组,并添加空值保护避免报错:

import React, {useMemo} from 'react'
import { useTable } from 'react-table'
import { COLUMNS } from './patternViewColumns'
import './table.css'

export default function PatternView(props) {
    const rawData = require('./data/data.json')
    // 提取Events数组,空值保护避免JSON结构异常时报错
    const eventsData = rawData?.[0]?.Events || []

    const columns = useMemo(() => COLUMNS, [])
    const data = useMemo(() => eventsData, [])

    const tableInstance = useTable({
        columns,
        data
    })

    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = tableInstance

    return (
        <table {...getTableProps()}>
            <thead>
                {headerGroups.map((headerGroup) => (
                    <tr {...headerGroup.getHeaderGroupProps()}>
                        {headerGroup.headers.map((column) => (
                            <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                        ))}
                    </tr>
                ))}
            </thead>
            <tbody {...getTableBodyProps()}>
                {rows.map((row) => {
                    prepareRow(row)
                    return (
                        <tr {...row.getRowProps()}>
                            {row.cells.map((cell) => {
                                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                            })}
                        </tr>
                    )
                })}
            </tbody>
        </table>
    )
}

关键修改说明

  • 数据源从整个JSON数组改为rawData[0].Events,确保表格拿到的是每条事件数据的数组
  • 移除了表头中多余的空<th>,避免表头多出无效列
  • 添加?.可选链和|| []默认值,防止JSON结构变化时页面崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 00:07:38