简体   繁体   English

从 NewsApi (react, axios) 获取数据

[英]Fetch data from NewsApi (react, axios)

I've started to learn to react and now I'm working on a code challenge.我已经开始学习做出反应,现在我正在应对代码挑战。

My task is to list data from the newsapi.org with Axios.我的任务是使用 Axios 列出来自 newsapi.org 的数据。 There are 10 articles to be displayed and the list should be extendable (load more).有 10 篇文章要显示,列表应该是可扩展的(加载更多)。

Now I can't get any further on the point of displaying the data.现在我无法进一步了解显示数据。

Where is my mistake?我的错误在哪里?

Here is my code:这是我的代码:

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;

You must use response.data.您必须使用 response.data。 articles not results文章不是结果

As Kevin mentioned, first you need to map over response.data.articles , but you must also return the mapped results, otherwise when you call .then to set the state it'll be undefined .正如凯文提到的,首先你需要映射response.data.articles ,但你还必须返回映射的结果,否则当你调用.then来设置状态时,它将是undefined Like this:像这样:

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 }));
}

That should work now.现在应该可以了。

Hi Try using the fetch() method see code below.您好 尝试使用 fetch() 方法,请参阅下面的代码。

Part of code from Andrei's robofriends tutorial.来自 Andrei 的机器人朋友教程的部分代码。 Used the same conete使用相同的锥体

 <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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM