为什么我的JSON响应返回未定义?



我试图在我的React Native应用程序中获取COVID数据,但每次我尝试检查响应时,控制台输出未定义的json变量:

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState({});
useEffect(() => {
fetch("https://api.covid19api.com/summary")
.then((response) => {
response.json();
})
.then((json) => {
console.log("json.. " + json);
setData(json);
}) 
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);

在第一个.then()中,您没有返回任何内容,因此undefined是隐式返回的。

应该返回reponse.json():

.then((response) => {
return response.json();
})

或短:

.then((response) => response.json())

最新更新