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

React JS中如何获取对象内部Items数组数据并渲染为表格

问题原因

  1. 你给出的示例数据结构存在语法笔误,正确格式应为{"body": "对应值", "Items": [{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}], "Count":2, "ScannedCount":2},确认实际返回数据符合该格式即可。
  2. 不需要对this.state.message调用Object.entries遍历全量键值对,你需要的表格数据直接存储在this.state.message.Items数组中,直接取用即可。
  3. 调用JSON.parse报错是因为该数据typeof已经是object,说明它已经是解析完成的JavaScript对象,JSON.parse仅用于处理JSON格式字符串,传入对象会触发语法错误。
  4. 之前通过data[1]拿到Items但无法访问内部值,是因为Object.entries返回的每一项是[键名, 键值]数组,你拿到的是Items数组本身,要访问内部属性需要继续遍历这个数组。

修复后的完整render代码

render() {
    // 直接取出Items数组,加兜底逻辑避免数据未加载时报错
    const items = this.state.message?.Items || [];
    // 动态表头:如果字段不固定可以用这行代码自动读取键名作为表头
    // const headers = items.length ? Object.keys(items[0]) : ['key1', 'key2'];
    return (
        <div>
            <div className="viewall">
                <table border="1" cellPadding="8" cellSpacing="0">
                    {/* 表头,根据实际字段调整即可 */}
                    <thead>
                        <tr>
                            <th>key1</th>
                            <th>key2</th>
                            {/* 动态表头写法:
                            {headers.map(header => <th key={header}>{header}</th>)} */}
                        </tr>
                    </thead>
                    <tbody>
                        {/* 遍历Items渲染每一行数据 */}
                        {items.map((item, index) => (
                            <tr key={index}>
                                <td>{item.key1}</td>
                                <td>{item.key2}</td>
                                {/* 动态单元格写法:
                                {headers.map(header => <td key={header}>{item[header]}</td>)} */}
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:15:04