首页 > 解决方案 > 如何在卡片上从 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)
  });

标签: jsonreactjsionic-frameworkaxiosrender

解决方案


在反应:

挂载时调用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;


推荐阅读