【发布时间】:2021-02-26 16:42:54
【问题描述】:
我试图用 react.js 获取 api,但在第一次渲染时它没有给出任何东西,而第二次渲染它给出了数据。这使得当我稍后尝试访问图像的数据时出现错误,TypeError: Cannot read property 'news.article' of undefined,因为它最初是空的。我该如何解决?
这是我的代码..
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => updateNews(data))
.catch((error) => console.log(error))
}, [])
return (
<>
</>
);
};
export default HomeContent;
【问题讨论】:
-
你不需要“解决”它。这就是它应该如何工作的方式。
-
这使得当我稍后尝试访问图像的数据时出现错误,TypeError: Cannot read property 'news.articles' of undefined, 因为它最初是空的。
-
重新编辑:在您与我们共享的代码中,您绝不会尝试读取
news的任何属性(更不用说news.articles,这样代码就不会产生该错误。 (如果news将获得一个名为articles的属性,那么将它初始化为一个空的array 是没有意义的)。 -
通常你会有一个额外的
loading状态,当请求完成时你设置为false。然后你可以渲染某种加载指示器,而loading仍然是true。对于更复杂的应用程序,您还需要一些状态来在获取数据时处理错误。 -
可以给我一个代码示例吗? @trixn
标签: javascript reactjs api fetch