json - 如何在卡片上从 axios.get 渲染 JSON?
问题描述
我可以在控制台中查看来自 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)
});
解决方案
在反应:
挂载时调用use effect,调用自定义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;
推荐阅读
- html - 网格区域不适应容器高度
- flutter - 如何在 Flutter 中去除 Razer 商户服务页面顶部的 header?
- python - 如何创建交互式脑形图?
- r - 使用 rowwise() 时如何处理整行?
- ios - 是否可以使用所有键获取 CNContact?
- ssl - OpenSSL 创建 pfx 证书
- apache-kafka - 用于 Kafka 消费者的反应性 Spring Cloud 功能在没有流结束的情况下提交偏移量
- javascript - React:为什么我的光标在输入修改后会跳到输入字段的末尾
- react-native - Expo 中的错误(React Navigation):检查 `ExpoRootComponent` 的渲染方法
- javascript - 如何修改现有数据,使用带有 JSON 的 if 条件