无法获得要在React中显示的NewsApi数据

问题描述 投票:0回答:2

我无法显示我的News Api数据...错误消息:“ TypeError:无法读取未定义的属性”映射“从新闻容器文件中。“

我认为我从New Api提取数据的方式出了问题。

news-api.js文件:

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;
};

news-container.js文件:

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;

news-card.js文件:

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;
reactjs api axios react-hooks
2个回答
0
投票

您需要更改此:

return  news.map(article =>
  <NewsCard  props={article} />)
}

对此:

return  news.article.map(item =>
  <NewsCard  props={item} />)
}

因为您将对象设置为状态而不是Articles数组。只需检查您的回复即可。


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;
};
© www.soinside.com 2019 - 2024. All rights reserved.