所以我尝试使用从 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;
关于reactjs - 尝试从 api 获取数据时出现未定义 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53998407/