React表格组件单层嵌套对象数据展示实现方案咨询
解决React表格展示单层嵌套对象数据的问题
首先得调整表头数据的结构——原来的纯字符串数组没法区分嵌套字段,改成包含显示标签和数据路径的对象数组,比如:
const theadData = [ { label: "接口名称", path: "name" }, { label: "租户ID", path: "tenant-id" }, { label: "管理状态", path: "if-admin-status" }, { label: "运行状态", path: "if-oper-status" }, { label: "主机接口", path: "host-inf" }, { label: "RX数据包", path: "rx-stats.rx-packets" }, { label: "RX每秒数据包", path: "rx-stats.rx-pps" }, { label: "RX字节数", path: "rx-stats.rx-bytes" }, { label: "TX数据包", path: "tx-stats.tx-packets" }, { label: "TX每秒数据包", path: "tx-stats.tx-pps" }, // 按需添加其他需要展示的嵌套字段 ];
然后写个简单的工具函数,用来根据路径从嵌套对象里取值:
const getNestedValue = (obj, path) => { return path.split('.').reduce((current, key) => { return current ? current[key] : ''; }, obj); };
接下来修改你的Table组件,适配新的表头结构:
import { v4 as uuidv4 } from 'uuid'; export default function Table({ theadData, tbodyData }) { // 嵌套字段取值函数 const getNestedValue = (obj, path) => { return path.split('.').reduce((current, key) => { return current ? current[key] : ''; }, obj); }; return ( <table style={{ border: "1px solid" }}> <thead style={{ border: "1px solid", backgroundColor: "rgb(10,110,253)", color: "white" }}> <tr style={{ border: "1px solid" }}> {theadData.map((heading) => ( <th key={heading.path}>{heading.label}</th> ))} </tr> </thead> <tbody> {tbodyData.map((row, rowIndex) => ( <tr key={rowIndex} style={rowIndex % 2 ? { backgroundColor: '#f2f2f2' } : null} > {theadData.map((col) => { const value = getNestedValue(row, col.path); return ( <td style={{ border: "1px solid" }} key={uuidv4()}> {value} </td> ); })} </tr> ))} </tbody> </table> ); }
核心逻辑说明
把表头里的path按.拆分(比如rx-stats.rx-packets拆成['rx-stats', 'rx-packets']),然后用reduce逐层访问对象属性,最终拿到嵌套字段的值。如果路径不存在或者中间属性为空,就返回空字符串避免页面报错。
如果不想改表头结构,也可以直接用带.的字符串数组(比如["name", "rx-stats.rx-packets"]),然后把表头文本做个转换(比如把rx-stats.rx-packets转成RX数据包),但用对象数组的方式更清晰,后续维护也更方便。
内容的提问来源于stack exchange,提问作者user2459924
相关产品推荐
相关产品推荐

