我无法显示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;
答案 0 :(得分:0)
您需要更改此内容:
return news.map(article =>
<NewsCard props={article} />)
}
对此:
return news.article.map(item =>
<NewsCard props={item} />)
}
因为您将对象设置为状态而不是Articles数组。只需检查您的回复即可。
答案 1 :(得分:0)
您必须访问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;
};
答案 2 :(得分:0)
我遇到了类似的问题,我无法获得正确的数据“无法读取未定义的属性'map'”我的代码如下:
NewsApp文件:
从'react'导入React,{useEffect,useState}; 从“ ./NewsCard.jsx”导入NewsCard;
功能NewsApp(){
const [news, setNews] = useState([]);
useEffect(() => {
getNews();
}, []);
const getNews = async () => {
const response = await fetch('http://newsapi.org/v2/top-headlines?country=us&apiKey=7f6de317d6ff4d3582ee52c9559f2c36');
const data = await response.json();
setNews(data)
}
return (
<div>
{news.articles.map(item =>
<NewsCard props={item} />)}
</div>
);
}
导出默认NewsApp;
如果有人知道可以解决这个问题,我将很感激