React请求Jikan API单条接口报animes.map is not a function错误
问题根因
报错Uncaught TypeError: animes.map is not a function的核心原因是Jikan API不同类型接口的返回结构不一致:
- 列表类接口(如
/top/anime、/genres/anime):响应体的data字段为数组类型,每个元素对应一条动漫/分类数据,符合你之前写的map遍历逻辑,因此可以正常运行 - 单资源接口(如
/people/{id}、/anime/{id}):响应体的data字段为单个对象类型,存储的是单个人物/单部动漫的详情,不是数组,数组原型上的map方法无法在对象上调用,因此抛出类型错误。
另外你贴的单部动漫接口示例地址https://api.jikan.moe/v4 /anime/38000中,v4和/anime之间多了一个空格,实际请求时会返回404,使用时需要删除多余空格。
解决方案
根据你的业务需求选择对应处理方式即可:
方案1:仅展示单条人物/动漫详情
不需要使用map遍历,直接渲染对象属性即可,参考修改后的代码:
const getSingleData = async () => { try { const response = await fetch('https://api.jikan.moe/v4/people/5579'); const res = await response.json(); return res; } catch (error) { console.error(error); } }; function App() { // 单条数据初始值设为空对象 const [currentItem, setCurrentItem] = useState({}); const fetchData = async () => { try { const res = await getSingleData(); setCurrentItem(res.data); } catch (error) { console.error(error); } }; useEffect(() => { fetchData(); }, []); return ( <> <header> <h1>Search Anime</h1> </header> <main> <article className="countries"> {/* 先判断数据加载完成再渲染,避免空对象读取属性报错 */} {currentItem.mal_id && ( <div key={currentItem.mal_id}> <h2>{currentItem.name}</h2> {/* 可按需渲染其他属性,比如人物生日、参演动漫列表等 */} </div> )} </article> </main> </> ); } export default App;
方案2:需要遍历单条接口返回的关联列表
比如人物接口返回的对象中,anime字段是该人物参与配音的动漫数组,你只需要在存状态时取到对应数组字段即可:
const fetchData = async () => { try { const res = await getSingleData(); // 取关联的动漫数组,兜底空数组避免报错 setAnimes(res.data.anime || []); } catch (error) { console.error(error); } };
通用兜底方案
如果需要兼容列表、单条两种接口的返回,可以在设置状态时做类型校验,保证状态始终为数组,不会触发map报错:
// 如果返回的data是数组就直接用,是对象就包装成单元素数组 setAnimes(Array.isArray(res.data) ? res.data : [res.data])
内容的提问来源于stack exchange,提问作者David Leihg
相关产品推荐
相关产品推荐

