首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从NewsApi获取数据(react,axios)

从NewsApi获取数据(react,axios)
EN

Stack Overflow用户
提问于 2020-03-06 16:04:49
回答 3查看 2.6K关注 0票数 1

我已经开始学习反应,现在我正在进行代码挑战。

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

现在我无法进一步了解显示数据的问题了。

我的错误在哪里?

这是我的代码:

代码语言:javascript
复制
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;
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-03-06 16:35:17

您必须使用response.data.articles而不是结果

票数 2
EN

Stack Overflow用户

发布于 2020-03-06 17:35:29

正如凯文所提到的,首先您需要在response.data.articles上映射,但也必须返回映射的结果,否则当您调用.then来设置状态时,它将是undefined。如下所示:

代码语言:javascript
复制
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 }));
}

现在该起作用了。

票数 0
EN

Stack Overflow用户

发布于 2020-04-16 08:53:24

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

部分代码来自安德烈的机器人朋友教程。用同样的圆柱体

代码语言:javascript
复制
<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;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60567710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档