reactjs - 无法从 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 个堆栈帧被折叠。
解决方案
.map()
是 JavaScript 中数组的一个函数 - 该 API 返回一个对象。
看起来您想要的是该docs
对象内的数组,因此请尝试将该行更改为:
{ recentArticles.docs.map(articles =>
该 API 返回的对象中的其他键与分页相关。您应该使用它们来创建分页控件,例如下一页、上一页链接等。
推荐阅读
- node.js - nodejs中的跨线程同步
- javascript - 如何刷新 Angular 上的 Font Awesome 图标?
- c++ - 使用一侧带有动态纹理的 DirectXTK 创建 3d 卡片
- python-3.x - 获取 selenium.common.exceptions.TimeoutException:消息:尝试通过链接文本单击元素时
- javascript - 反应模态打开第二个模态但第二个模态不起作用
- javascript - 在 webstrom 中找不到可执行节点问题
- django-rest-framework - 我如何决定在通用视图类或序列化程序类上覆盖 create() 方法
- python - 获取布尔数组,指示数组中哪些元素属于列表
- complexity-theory - 最短哈密顿路径是 NP 难的吗?
- c# - C# WPF:当窗口关闭时,如何调用具有数据绑定的方法?