React使用useEffect获取API数据时出现TypeError: posts.map is not a function错误
问题解决:Posts.map is not a function
问题出在接口返回的数据结构上:https://reqres.in/api/users返回的是一个包含用户数组的对象,真正的用户列表在res.data.data字段里,而你现在把整个外层对象赋值给了posts状态,导致posts变成了对象,对象没有map方法,所以报错。
修改代码里的setPosts部分,改为赋值res.data.data即可:
import React ,{useState,useEffect} from 'react'; import axios from 'axios'; function DataFetching() { const[posts,setPosts]= useState([]) useEffect(()=>{ axios.get('https://reqres.in/api/users') .then(res=>{ console.log(res) // 改为res.data.data,取到真正的用户数组 setPosts(res.data.data) }) .catch(err=> console.log(err) ) },[]) return ( <div> <ul> { posts.map(post=><li key={post.id}>{post.email}</li>) } </ul> </div> ); } export default DataFetching;
你可以先打印res.data的结构确认:外层对象包含data、page、per_page等字段,其中data才是需要遍历的用户数组。
内容的提问来源于stack exchange,提问作者Sajitha Anu
相关产品推荐
相关产品推荐

