【发布时间】:2020-05-14 00:52:54
【问题描述】:
我想做的是从天气 API 获取数据,但是在第一次渲染时会发生“数据”状态为空,而在第二次渲染时会调用 API 并设置数据。这使得当我稍后尝试访问图像的数据时,我收到错误TypeError: Cannot read property 'weather' of undefined,因为它最初是空的。不知何故,我需要跟踪渲染发生的次数或更改我获取数据的方式。我认为带有空列表的useEffect 作为第二个参数将充当componentDidMount。这是我的代码:
import React, {useState, useEffect} from 'react';
export default function App() {
const useFetch = () =>{
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect( () => {
async function fetchData(){
const response = await fetch('https://api.weatherbit.io/v2.0/forecast/hourly?city=Chicago,IL&key=XXX&hours=24');
const json = await response.json();
setData(json.data);
setLoading(false);
}
fetchData();
}, []);
return {data, loading};
}
const convert = (c) =>{
let f = (c*(9/5))+32;
return f
}
const {data, loading} = useFetch();
console.log(data)
return (
<div>
<img src={'https://www.weatherbit.io/static/img/icons/'+data[0].weather.icon+'.png'}/>
<h1>{loading ? 'Loading...' : ''}</h1>
</div>
)
}
【问题讨论】:
标签: javascript reactjs react-hooks