首页 > 解决方案 > 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;

标签: reactjs

解决方案


尝试改变

const articles = response.data;

const articles = response.data.articles;

这是因为 api 在文章键中返回带有响应的 JSON 输出。


推荐阅读