首页 > 解决方案 > this.state.xxx.map 不是函数

问题描述

我正在尝试显示来自该州的数据,但是当我尝试映射数据时,出现错误提示

this.state.xxx.map 不是函数

import React, { Component } from 'react';
import axios from 'axios';

export default class Content extends Component {
    constructor(){
        super();
        this.state = {
            gifs: [{}]
        }
    }

    componentDidMount(){
        axios.get('https://api.giphy.com/v1/gifs/random?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G')
        .then( response => {
            this.setState({ gifs: response.data.data})
        })
        .catch(function(error){
          console.log(error);  
        })
    }

    render() {
        return (
            <div>
                {this.state.gifs.map( gif =>
                    <p>{gif.url}</p>
                    )}
            </div>
        );
    }
}

这是我收到的错误消息

标签: javascriptreactjs

解决方案


这是工作演示:

api 将响应单个 gif 图像并且它是对象,在您的状态 gifs 是数组,因此您必须将新对象推送到 gifs 数组中,或者您可以使用扩展运算符“...”[...this.state.gifs,newGIFobject]添加到 gif 数组中。

const {Component} = React;

class Content extends Component {
    constructor(){
        super();
        this.state = {
            gifs:[]
        }
    }

    componentDidMount(){
        axios('https://api.giphy.com/v1/gifs/random?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G')
        .then( response => {
            console.log(response);
            this.setState({ gifs: [...this.state.gifs, response.data.data]})
        })
        .catch(function(error){
          console.log(error);  
        })
    }

    render() {
        return (
            <div>
                {this.state.gifs.map(gif => <p>{gif.url}</p>)}
                    
            </div>
        );
    }
}


// Render it
ReactDOM.render(
  <Content />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="react"></div>


推荐阅读