【问题标题】:Fetch data from NewsApi (react, axios)从 NewsApi (react, axios) 获取数据
【发布时间】:2020-06-19 09:42:09
【问题描述】:

我已经开始学习做出反应,现在我正在处理代码挑战。

我的任务是使用 Axios 列出来自 newsapi.org 的数据。有 10 篇文章要显示,列表应该是可扩展的(加载更多)。

现在我无法进一步了解如何显示数据。

我的错误在哪里?

这是我的代码:

import React from "react";
import axios from "axios";

class App extends React.Component {
  state = {
    articles: [],
    isLoading: true,
    errors: null
  };

  getArticles() {
    axios
      .get(
        "http://newsapi.org/v2/everything?q=ai&apiKey=XXXXXXXXX"
      )
      .then(response =>
        response.data.results.map(article => ({
          date: `${article.publishedAt}`,
          title: `${article.title}`,
          url: `${article.url}`
        }))
      )
      .then(articles => {
        this.setState({
          articles,
          isLoading: false
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }

  componentDidMount() {
    this.getArticles();
  }

  render() {
    const { isLoading, articles } = this.state;
    return (
      <React.Fragment>
        <h2>#AI</h2>
        <div>
          {!isLoading ? (
            articles.map(article => {
              const { date, title, url } = article;
              return (
                <div key={title}>
                  <p>{date}</p>
                  <p>{title}</p>
                  <p>{url}</p>
                </div>
              );
            })
          ) : (
            <p>Loading...</p>
          )}
        </div>
      </React.Fragment>
    );
  }
}
export default App;

【问题讨论】:

  • 嗨!隐藏你的 api 密钥;)
  • @AljažMedič 删除您的评论。

标签: javascript reactjs api axios fetch


【解决方案1】:

您必须使用 response.data。文章而不是结果

【讨论】:

  • 谢谢,这很有道理。但是数据还是没有显示出来。
  • 尝试记录对象,看看它在哪里停止成为你想要的样子......另外,最好检查一下 if(response.data.articles),然后返回
  • 同意,一步一步调试。在操作数据之前添加 console.log。
  • 天哪,伙计们。问题是网址..我将http更改为https并且它可以工作。感谢您的帮助!
【解决方案2】:

正如 Kevin 所说,首先您需要映射 response.data.articles,但您还必须返回映射结果,否则当您调用 .then 设置状态时,它将是 undefined。像这样:

getArticles() {
  axios
    .get(
      "https://newsapi.org/v2/everything?q=ai&apiKey=YOURAPIKEYGOESHERE"
    )
    .then(response => {
      return response.data.articles.map(article => ({
        date: `${article.publishedAt}`,
        title: `${article.title}`,
        url: `${article.url}`
      }));
    })
    .then(articles => {
      this.setState({
        articles,
        isLoading: false
      });
    })
    .catch(error => this.setState({ error, isLoading: false }));
}

现在应该可以了。

【讨论】:

    【解决方案3】:

    您好尝试使用 fetch() 方法,请参阅下面的代码。

    来自 Andrei 的机器人朋友教程的部分代码。使用相同的锥体

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
    
    import React, {Component} from 'react';
    import CardList from '../components/Cardlist';
    import SearchBox from '../components/SearchBox';
    import './App.css';
    import Scroll from '../components/Scroll';
    import ErrorBoundry from '../components/ErrorBoundry';
    
    
    class App extends Component {
        //add state
        constructor() {
            super()
            this.state = {
                articles: [],
                searchfield: ''
            }
        }
    
        componentDidMount() {
            //fetch is a window object
            fetch('https://newsapi.org/v2/top-headlines?country=gb&category=business&apiKey=yourapikey')
            .then(response => response.json()) //convert to json
            //.then(users =>this.setState({ news: users}));
            .then(res => {
                const articles = res.articles;
                // Set state with result
                console.log(articles);
                this.setState({ articles: articles });
              })
        }
    
    
        //event for searchbox change
        //not part of react component so use arrow function
        onSearchChange = (event) => {
            this.setState({ searchfield: event.target.value})
        }
    
        render() {
            const filteredNews = this.state.articles.filter(i => {
                return i.source.name.toLowerCase().includes(this.state.searchfield.toLowerCase()); //change name to source?
            })
            console.log(filteredNews);
            if (this.state.articles.length === 0) {
                return <h1>Loading Robots</h1>
            } else {
                return (
                    <div className='tc'>
                        <h1 className='f1'>Top Headlines</h1>
                        <SearchBox  searchChange={this.onSearchChange}/>
                        <Scroll>
                            <ErrorBoundry>
                                <CardList articles={filteredNews}/>
                            </ErrorBoundry> 
                        </Scroll>
                    </div>
                    
                );
            }
            
        }   
    }
    
    export default App;

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2018-01-31
      • 2020-07-20
      • 2022-01-04
      • 2021-07-27
      • 2020-12-05
      • 2021-05-19
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多