【发布时间】:2020-06-19 09:42:09
【问题描述】:
我已经开始学习做出反应,现在我正在处理代码挑战。
我的任务是使用 Axios 列出来自 newsapi.org 的数据。有 10 篇文章要显示,列表应该是可扩展的(加载更多)。
现在我无法进一步了解如何显示数据。
我的错误在哪里?
这是我的代码:
import React from "react";
import axios from "axios";
class App extends React.Component {
state = {
articles: [],
isLoading: true,
errors: null
};
getArticles() {
axios
.get(
"http://newsapi.org/v2/everything?q=ai&apiKey=XXXXXXXXX"
)
.then(response =>
response.data.results.map(article => ({
date: `${article.publishedAt}`,
title: `${article.title}`,
url: `${article.url}`
}))
)
.then(articles => {
this.setState({
articles,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
componentDidMount() {
this.getArticles();
}
render() {
const { isLoading, articles } = this.state;
return (
<React.Fragment>
<h2>#AI</h2>
<div>
{!isLoading ? (
articles.map(article => {
const { date, title, url } = article;
return (
<div key={title}>
<p>{date}</p>
<p>{title}</p>
<p>{url}</p>
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
export default App;
【问题讨论】:
-
嗨!隐藏你的 api 密钥;)
-
@AljažMedič 删除您的评论。
标签: javascript reactjs api axios fetch