我能够在控制台中查看来自api的数据,但是无法呈现在UI中接收到的数据。接下来我该怎么办?
const news = 'http://newsapi.org/v2/top-headlines?country=us'
axios
.get(news)
.then(response => {
const articles = response.data.articles[0].title;
console.log(articles)
})
.catch((error) => {
console.log(error)
});
答案 0 :(得分:2)
反应中:
使用效果在挂载时被调用,调用自定义data()异步函数以使用axios,将其与useState一起存储在本地状态,然后在渲染器中通过状态进行映射
import React, { FC, useEffect, useState } from 'react';
import axios from 'axios';
const NEWS = 'http://newsapi.org/v2/top-headlines?country=us';
const SampleScreen: FC = () => {
const [news, setNews] = useState([]);
useEffect(() => {
const data = async () => {
try {
const res = await axios.get(NEWS);
const { articles } = res.data;
if (articles) {
setNews(articles);
}
} catch (err) {
throw new Error(err);
}
};
data();
}, []);
return (
<div>
{news.map(({ title, content, date }) => {
return (
<div key={date}>
<strong>{title}</strong>
<p>{content}</p>
</div>
);
})}
</div>
);
};
export default SampleScreen;