React Native中Cannot read property 'json' of undefined错误求助
解决React Native中fetch调用的"Cannot read property 'json' of undefined"错误
你的代码报错的核心原因是错误解构了fetch的返回值:原生fetch API直接返回的是Response对象本身,并非一个包含response属性的对象。你写的const {response} = await fetch(url)会把response解析为undefined,后续调用response.json()自然就会抛出"Cannot read property 'json' of undefined"的错误。
修正后的代码如下:
import { useEffect, useState } from "react"; function useFetch (url) { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(); const fetchData = async () => { try { // 去掉解构,直接接收fetch返回的Response对象 const response = await fetch(url); // 先检查响应状态是否成功,避免无效状态下解析JSON if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const convertedData = await response.json(); setData(convertedData); setLoading(false); } catch (error) { setError(error.message); setLoading(false); } } useEffect(() => { fetchData(); }, [url]) // 将url加入依赖数组,确保url变化时重新发起请求 return {data, loading, error}; } export default useFetch;
额外补充两个实用优化:
- 增加
response.ok状态检查,避免在请求返回4xx/5xx错误状态时继续解析JSON,减少额外报错 - 把
url加入useEffect的依赖数组,符合React Hooks的依赖规范,确保传入的url更新时能自动重新请求
内容的提问来源于stack exchange,提问作者melissaT
相关产品推荐
相关产品推荐

