reactjs - React JS 错误:this.state.data.map 不是函数
问题描述
我是 React 的新手,在尝试从 API 映射一些数据时出现了这种情况。我已将状态设置为数组,但仍然出现此错误。
import React, { Component } from 'react';
import axios from 'axios';
class Test extends Component {
state = {
articles: [],
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response.data;
this.setState({ articles });
})
}
render() {
return (
<div>
<ul>
{this.state.articles.map(article => <li><a href={`${article.url}`}>{article.title}</a></li>)}
</ul>
</div>
)
}
}
export default Test;
解决方案
尝试改变
const articles = response.data;
至
const articles = response.data.articles;
这是因为 api 在文章键中返回带有响应的 JSON 输出。
推荐阅读
- html - 在应用分页 CSS 时修复下划线
- excel - 计算列以根据三个条件对所有匹配值求和
- z3 - Dafny 作为 SAT-QBF 求解器没有给出正确的结果
- python - 从python中的列表中删除错误重复值的问题
- php - preg_split 返回一个非预期的数字
- visual-studio-code - zsh Git 信息中的星号
- node.js - Node JS 多请求处理
- amazon-web-services - x509:证书由未知权威签名(可能是“crypto/rsa:验证错误”的 bcz,同时尝试验证候选权威证书“kubernetes”)
- react-native - 反应本机推送通知启用/禁用
- api - 谷歌日历 API 拒绝 Errno 13 权限