React报Objects are not valid as a React child错 如何渲染接口数组为表格
问题原因
你触发报错的核心原因是:将包含Items、Count、ScannedCount的完整对象直接作为React子元素渲染,React原生不支持直接渲染对象类型的内容。
解决方案
第一步:修改setState赋值逻辑
你不需要将整个convertString对象存入state,只需要提取其中你需要的Items数组即可,修改getData方法中的setState代码:
// 原代码 // this.setState({message: convertString}); // 替换为 this.setState({message: convertString.Items || []});
加|| []是为了做兜底兼容,避免接口返回没有Items字段时,后续遍历数组出现报错。
另外注意你原代码中console.log(convertString));多了一个右括号,属于语法错误,需要删掉多余的括号。
第二步:修改render逻辑渲染表格
将render方法中直接渲染this.state.message的部分,替换为表格遍历逻辑即可:
render() { return( <div> <table style={{borderCollapse: 'collapse'}} border="1"> <thead> <tr> <th>key1</th> <th>key2</th> {/* 可根据实际字段新增列 */} </tr> </thead> <tbody> {this.state.message.map((item, index) => ( // 实际生产环境建议用item的唯一id作为key,不要用index <tr key={index}> <td>{item.key1}</td> <td>{item.key2}</td> {/* 对应渲染每个字段的内容 */} </tr> ))} </tbody> </table> </div> ) }
内容的提问来源于stack exchange,提问作者Audrey Wong
相关产品推荐
相关产品推荐

