React调用Last.fm API报错:Objects are not valid as React child求解
解决React调用Last.fm API的渲染错误及数据获取问题
错误原因
你遇到的Objects are not valid as React child错误,核心问题有两个:
- 你把API返回的整个JSON对象存到了
items状态里,但items被定义为Array<String>类型,实际存的是嵌套对象,之后用Array.from(items)处理对象,遍历的是对象的键,每个遍历项都是对象,React无法直接渲染对象。 - 真正的曲目数组不在根JSON对象里,而是藏在
json.tracks.track路径下。
修正步骤及代码
1. 修正状态类型与赋值逻辑
调整state的类型定义匹配曲目数据结构,同时在fetch回调里正确提取曲目数组;
2. 正确渲染曲目与艺术家信息
直接对曲目数组做map遍历,给每个列表项添加唯一key,避免React警告,同时正确访问item.name(曲目名)和item.artist.name(艺术家名)。
修改后的完整代码:
// 定义类型确保类型安全 interface Artist { name: string; mbid?: string; url: string; } interface Track { name: string; duration: string; playcount: string; listeners: string; mbid?: string; url: string; streamable: { "#text": string; fulltrack: string }; artist: Artist; image: Array<{ "#text": string; size: string }>; } class App extends React.Component<{}, { items: Track[]; DataisLoaded: boolean }> { constructor(props: any) { super(props); this.state = { items: [], DataisLoaded: false }; } componentDidMount() { fetch("https://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=6808816d086d4c48075217bd2cc178a1&format=json") .then((res) => res.json()) .then((json) => { // 提取正确的曲目数组 this.setState({ items: json.tracks.track, DataisLoaded: true }); }) // 捕获请求失败情况,避免页面一直处于加载状态 .catch(err => { console.error("请求失败:", err); this.setState({ DataisLoaded: true }); }) } render() { const { DataisLoaded, items } = this.state; if (!DataisLoaded) return <div><h1>请稍等...</h1></div>; if (items.length === 0) return <div><h1>暂无数据</h1></div>; return ( <div className="App"> <h1> React获取API数据示例 </h1> <ul> {items.map((item) => ( <li key={item.url}> 曲目:{item.name},艺术家:{item.artist.name} </li> ))} </ul> </div> ); } }
关键说明
- 数据提取:API返回的JSON结构是
{ tracks: { track: [...] } },必须通过json.tracks.track拿到曲目数组; - 类型定义:添加
Artist和Track接口可以让Typescript帮你检查数据访问是否正确,避免拼写错误; - 错误处理:加上
catch块处理请求失败的情况,提升用户体验; - 列表key:给map生成的每个元素添加唯一key,这里用
item.url是因为每个曲目url都是唯一的。
内容的提问来源于stack exchange,提问作者Polina
相关产品推荐
相关产品推荐

