React useAsync无法接收fetchData返回数据的问题求助
问题分析与解决
核心问题:重复调用res.json()
你代码里的console.log(res.json());和return res.json();是导致data为undefined的直接原因。因为res.json()会一次性消费响应体流,第一次调用后,响应体已经被读取完毕,第二次调用res.json()会返回一个状态为resolved但值为undefined的Promise,所以useAsync最终拿到的data就是undefined。
另外,console.log(res.json())打印的其实是一个Promise对象,你能看到数据是因为浏览器控制台会展开Promise的resolved值,但这并不代表它同步返回了数据。
修复代码
把res.json()的结果存储到变量中,再复用这个变量:
const fetchData = async () => { const apiUrl = "http://localhost:8080/user/natt@gmail.com"; const requestOptions = { method: "GET", headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, "Content-Type": "application/json", }, }; const res = await fetch(apiUrl, requestOptions); if (!res.ok) throw new Error(res.statusText); // 只调用一次res.json(),存储结果 const responseData = await res.json(); console.log(responseData); // 这里打印实际数据 return responseData; } const { data, error, isLoading } = useAsync({ promiseFn: fetchData }); console.log(data); if (isLoading) return <Grid>"Loading..."</Grid>; if (error) return <Grid>Something went wrong: {`${error.message}`}</Grid>; if (data) return(<Grid>"main code"</Grid>)
额外注意点
- 函数名拼写:你写的
fecthData是拼写错误,应该是fetchData(规范起见建议修正)。 - 确认
useAsync的参数格式:如果使用的是react-use库的useAsync,正确用法应为const { data, error, isLoading } = useAsync(fetchData);,无需包裹成{ promiseFn: fetchData },需要根据你使用的具体库调整参数格式。
内容的提问来源于stack exchange,提问作者Nattawut Rodthong
相关产品推荐
相关产品推荐

