【问题标题】:Having trouble fetching from an api not sure what I am doing wrong?无法从 api 获取不确定我做错了什么?
【发布时间】:2019-06-02 18:29:31
【问题描述】:

我正在尝试从 api 获取并显示我正在获取的数据。我已经尝试使用带有 promises 和 axios 的常规 fetch 并且它似乎没有做任何事情。我使用 .map() 方法,我得到错误 map is not a function。

我已经尝试使用 fetch 和 axios 来尝试从 api 获取数据。


    import React, { Component } from 'react';



    class RecentNews extends Component {
        state = {
          recentArticles: [],
          recentReports: [],
          isLoaded: false,
        }


    componentDidMount(){
      fetch(`https://spaceflightnewsapi.net/api/v1/articles?page=1`)
          .then(response => response.json())
          .then(json => this.setState(
            { recentArticles: json,
              isLoaded: true,
            }
          ))
    }


    render(){

      let { recentArticles, isLoaded } = this.state

      if (!isLoaded) {
        return <h1>Loading.....</h1>
          }

      else {

      return(
        <div className="recentnews">
        <div>
        { recentArticles.map(articles =>
          <p>{articles.title}</p>
        )


        }
        </div>

            </div>

          )
        }
      }
    }


    export default RecentNews

这是我遇到的错误

TypeError:recentArticles.map 不是函数

▶ 17 个堆栈帧被折叠。

【问题讨论】:

  • 检查响应结构 - 不是数组

标签: reactjs api fetch-api


【解决方案1】:

.map() 是 JavaScript 中的数组函数 - API 返回一个对象。

看来您想要的是该对象内的docs 数组,因此请尝试将该行更改为:

{ recentArticles.docs.map(articles =>

该 API 返回的对象中的其他键与分页有关。您应该使用它们来创建分页控件,例如下一页、上一页链接等。

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多