React类组件使用Axios异步获取API数据时出现渲染错误求助
React类组件用Axios+async/await调用API渲染时报错的解决
错误信息
Uncaught Error: Objects are not valid as a React child (found: object with keys {dhcp_lease_count, new_dhcp_lease_count, unracked_device_count, nodediscover_count, site_data}). If you meant to render a collection of children, use an array instead.
问题代码
组件中直接尝试渲染整个API返回的对象,触发了报错:
class MainContent extends Component { constructor(props) { super(props); this.state = { data: {}, isLoaded: false, access_token: "my_token_xxxxx", } } componentDidMount = () => { this.getData() } getData = async () => { try { axios.defaults.headers.common['Authorization'] = "Token " + this.state.access_token; const res = await axios.get("http://localhost:7001/api/plugins/dashboard"); this.setState({isLoaded: true, data: res.data}) } catch (error) { console.log(Object.keys(error), error.message); } } render() { const { isLoaded, data } = this.state; return ( <div> {isLoaded ? <h3>{data}</h3> : <h3>Loading...</h3>} </div>); } }
API返回的数据结构
{ "dhcp_lease_count": 169, "new_dhcp_lease_count": 19, "unracked_device_count": 4, "node_count": 135, "site_data": [ { "site_temp_avg": 0, "site_rack_count": 0, "site_utilization": 0, "site_device_count": 0 }, { "site_temp_avg": "70.6", "site_rack_count": 8, "site_utilization": 57.375, "site_device_count": 167 }, { "site_temp_avg": 0, "site_rack_count": 0, "site_utilization": 0, "site_device_count": 0 } ] }
错误原因
React无法直接渲染JavaScript对象,必须提取对象中的具体属性值来渲染。原代码里<h3>{data}</h3>直接把整个API返回的对象作为React子元素,这就触发了报错。
解决方法
修改渲染逻辑,提取对象中的各个属性值单独展示;对于数组类型的site_data,用map遍历生成表格行:
return ( <div> <h3>DHCP租约数 - {data['dhcp_lease_count']}</h3> <h3>新DHCP租约数 - {data['new_dhcp_lease_count']}</h3> <h3>未上架设备数 - {data['unracked_device_count']}</h3> <h3>待发现节点数 - {data['nodediscover_count']}</h3> <table> <tbody> {data["site_data"].map((row) => ( <tr key={row.site_temp_avg + row.site_device_count}> {Object.values(row).map((val) => ( <td style={{padding: '20px'}}>{val}</td> ))} </tr> ))} </tbody> </table> </div>);
注意:原代码中
row.site_id不存在,建议用每个site对象的唯一组合值作为key,避免React的key警告。
内容的提问来源于stack exchange,提问作者Ricky S
相关产品推荐
相关产品推荐

