首页 > 解决方案 > 无法从 api 获取不确定我做错了什么?

问题描述

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

我尝试使用 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

这是我得到的错误

类型错误:recentArticles.map 不是函数

▶ 17 个堆栈帧被折叠。

标签: reactjsapifetch-api

解决方案


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

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

{ recentArticles.docs.map(articles =>

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


推荐阅读