reactjs - 尝试从 api 获取数据时未定义 - React
问题描述
所以我试图用从 API 获得的数据设置一个变量。
当我通过控制台将其登录到我的浏览器时,一切正常,但是当我尝试在 React 上设置我的变量时,该变量最终无法识别。有人能告诉我我在这里想念什么吗?
这是我的代码:
import React from 'react'
let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}
getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}
export default NewsApi
解决方案
您的 getNews 函数是异步的。您应该使用状态来保存数据。因此,一旦获取数据,您就可以使用组件中的数据。
import React from 'react';
class NewsApi extends React.Component {
constructor(props) {
super(props);
this.state = {
news: []
};
this.getNews = this.getNews.bind(this);
}
componentDidMount() {
this.getNews()
}
getNews() {
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
.then(res => res.json())
.then((data) => {
this.setState({news:data.articles});
});
}
render() {
console.log(this.state.news)
return (
<div></div>
);
}
}
export default NewsApi;
推荐阅读
- swift - 如何在 Metal 中硬编码纹理?如何在不加载外部资源的情况下创建纹理?
- core-ui - 关于侧边栏顶部的标题 - CoreUI
- flutter - 启用仅在 Flutter 中的某些小部件中滑动
- tomcat - org.apache.catalina.LifecycleException: 无法启动组件 [StandardEngine [catalina].standardHost[localhost].StandardContext [/bonita]
- css - 在边界半径之外的点击在 Chrome 中的行为与在 Firefox 中的行为不同
- vba - 文件夹选择器 - 下标超出范围
- python-3.x - 从终端和 vim 运行 Python 脚本会给出不同的输出
- c++ - 对 C++ 中 Hash Table 的基础知识感到困惑
- firebase - 如何为特定用户设置 Firebase 存储规则
- python - python3 错误:无效模式 %r" % 模式,试图在 os.popen 中使用对象