我无法显示我的News Api数据...错误消息:“ TypeError:无法读取未定义的属性”映射“从新闻容器文件中。“
我认为我从New Api提取数据的方式出了问题。
import axios from "axios";
export const getNews = async () => {
const result = await axios
.get("https://newsapi.org/v2/everything?q=bitcoin&from=2019-12-15&sortBy=publishedAt&apiKey=...")
.then(function(response) {
// handle success
console.log(response);
});
return result;
};
import React, { useEffect, useState } from "react";
import { getNews } from "../news-api";
import NewsCard from "./NewsCard.js";
function NewsContainer() {
const [news, setNews] = useState([]);
useEffect(() => {
getNews().then(data => setNews(data));
}, []);
return news.map(article => <NewsCard props={article} />);
}
export default NewsContainer;
import React from "react";
import "./card.css";
function NewsCard(props) {
return (
<div className="cardWrapper">
<div className="cards">
<img src="article.urlToImage" alt="" />
<h2>{props.article.title}</h2>
<p>{props.article.description}text</p>
<a className="aColor" href={props.article.url}>
Read More
</a>
</div>
</div>
);
}
export default NewsCard;
您需要更改此:
return news.map(article =>
<NewsCard props={article} />)
}
对此:
return news.article.map(item =>
<NewsCard props={item} />)
}
因为您将对象设置为状态而不是Articles数组。只需检查您的回复即可。
您必须访问Axios响应的data
才能获取实际的响应有效负载。
import axios from "axios";
export const getNews = async () => {
const response = await axios.get("https://newsapi.org/v2/everything?q=bitcoin&from=2019-12-15&sortBy=publishedAt&apiKey=...");
return response.data;
};