【发布时间】:2020-04-11 13:08:56
【问题描述】:
我正在使用 React Hook 通过本机 fetch 方法从 JSON 对象中获取数据。
const COVID_API_URL = "https://api.covid19api.com/summary";
const [infected, setInfected] = useState([]);
async function fetchData() {
const response = await fetch(COVID_API_URL);
response.json().then(response => setInfected(response));
}
useEffect(() => {
fetchData();
}, []);
console.log(infected.Global.TotalConfirmed);
当我 console.log 来自 TotalConfirmed 的值时,我得到了正确的结果,但是当我刷新浏览器时,我不断得到:
TypeError: Cannot read property 'TotalConfirmed' of undefined
有人知道为什么会这样吗?我用的是 Gatsby.js 默认启动器,和这个有关系吗?
【问题讨论】:
-
我无法理解接受的答案如何解决问题,因为这里的问题是您正在访问一个不存在的值。不要假设您将始终获得正确的数据,始终验证您的数据。
标签: javascript reactjs fetch react-hooks gatsby