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

向ReactTable组件传入数据后出现渲染错误的原因是什么?

问题解决:React-Table + MaterialUI 传入非空数据报错

核心错误原因

你的ReactTable组件里存在类型标注错误:遍历表头列时,把column的类型写成了HeaderGroup,但实际上headerGroup.headers的每一项是Column类型,类型不匹配导致渲染非空数据时触发报错。空数组时不报错是因为此时rows为空,行渲染逻辑不会执行,表头的类型错误没被触发。

修正步骤

  1. 修正表头列的类型标注
    把headerGroup.headers.map((column: HeaderGroup)改成headerGroup.headers.map((column: Column),匹配正确的类型。

  2. 优化数据类型定义(可选但推荐)
    将组件props里的data: any替换为更严谨的类型,比如定义对应数据结构的接口:

interface TransactionData {
  date: string;
  type: string;
  amount: string;
  status: string;
}

再把props的data类型改为TransactionData[],避免any带来的类型隐患。

  1. 保留正确的行渲染逻辑
    你代码里prepareRow(row)的调用时机是对的,放在每一行渲染前即可,无需修改。

修正后的完整ReactTable组件代码

import {Stack, Table, TableBody, TableCell, TableHead, TableRow} from "@mui/material";
import {Cell, Column, HeaderGroup, Row, useTable} from "react-table";

// 自定义数据接口,规范数据结构
interface TransactionData {
  date: string;
  type: string;
  amount: string;
  status: string;
}

const ReactTable = ({columns, data}: {columns: Column[]; data: TransactionData[]}) => {
    const {getTableProps, getTableBodyProps, headerGroups, rows, prepareRow} = useTable({columns, data});

    return (
        <Stack>
            <Table {...getTableProps()}>
                <TableHead>
                    {headerGroups.map((headerGroup) => (
                        <TableRow {...headerGroup.getHeaderGroupProps()}>
                            {/* 修正类型标注为Column */}
                            {headerGroup.headers.map((column: Column) => (
                                <TableCell {...column.getHeaderProps()} align='center'>{column.render('Header')}</TableCell>
                            ))}
                        </TableRow>
                    ))}
                </TableHead>
                <TableBody {...getTableBodyProps()}>
                    {rows.map((row: Row) => {
                        prepareRow(row);
                        return (
                            <TableRow {...row.getRowProps()}>
                                {row.cells.map((cell: Cell)=>(
                                    <TableCell {...cell.getCellProps()}>{cell.render('cell')}</TableCell>
                                ))}
                            </TableRow>
                        )
                    })}
                </TableBody>
            </Table>
        </Stack>
    )
}
export default ReactTable;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:45