从API获取数据:数组和映射函数出现问题



我是一个初学者,对嵌套数组有问题。

这是API,我想从中获取一些信息,我有时已经做了很多次,但通常只是一个数组或单个信息。我已经尝试了很多方法来解决它,但我不知道如何更改代码以获得正确的回复:名称、标题、说明、urlToImage。

我想const[news,setNews]=useState([](有问题;并且可以使用Effect(((=>{获取新闻((;},[](;

我不知道用更多的嵌套数组而不是"[]"放什么。

下面是我的代码(包括API(。

NewsApp.jsx:

import React, { useEffect, useState } from 'react';
import NewsCard from "./NewsCard.jsx";

function 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)
console.log(data)
}

return (
<div>
{news.map(item =>
<NewsCard 
name={item.articles[0].source.name}
title={item.articles[0].title}
description={item.articles[0].description}
urlToImage={item.articles[0].urlToImage} />)}
</div>
);
}
export default NewsApp;

以及下面的NewsCard.jsx:

import React from 'react';
function NewsCard(props) {
return(
<div>
<div>
<h2>{props.item.name}</h2>
<h4>{props.item.title}</h4>
<p>{props.description}</p>
<a href={props.urlToImage}></a>
</div>
</div>
);
}
export default NewsCard;

如果有人能帮助我,我将不胜感激,因为这个应用程序无法完成我的整个项目。

看起来像是您在对象上使用的API返回,而不是数组。我还没有测试,但我会尝试以下

import NewsCard from "./NewsCard.jsx";
function 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.articles)
console.log(data)
}

return (
<div>
{news.map(article =>
<NewsCard 
name={article.source.name}
title={article.title}
description={article.description}
urlToImage={article.urlToImage} />)}
</div>
);
}
export default NewsApp;

请注意,当您调用setNews((时,您将使用data.articles,它是一个数组。我使用forEach,而不是映射来迭代文章。让我知道结果如何。

编辑:看起来你在React中使用了.map,而不是.forEach。

最新更新