未捕获的TypeError:this.state.imgData.map不是函数

时间:2019-07-17 21:25:20

标签: reactjs laravel

此处是我的图像数据文件

imageData = [
        {
            id: 1,
            imgName: "Apple",
            imgFile: "apple.jpg",
            imgQuestion: "Which fruit is this",
            imgAnswer: "This is an Apple"
        },
        {
            id: 2,
            imgName: "Orange",
            imgFile: "orange.jpg",
            imgQuestion: "What is the color of Orange",
            imgAnswer: "The color of orange os orange"
        },
        {
            id: 3,
            imgName: "Mango",
            imgFile: "mango.jpg",
            imgQuestion: "Do you like Mangoes",
            imgAnswer: "Yes I like Mangoes"
        }
    ]

我不知道为什么我的代码在浏览器控制台中显示错误消息:

  

未捕获的TypeError:this.state.imgData.map不是函数

import React, { Component } from 'react';

import Jokes from './../components/Jokes';
import Data from './../data';

export default class Index extends Component {

    constructor() {
        super()
        this.state = {
            imgData: Data
        }
    }

    render() {
        const imgDataItem = this.state.imgData.map(item => {
            <Jokes  data={{key: this.item.id}}
                    data={{
                        img: this.item.imgName,
                        imgFileName: this.item.imgFile,
                        question: this.item.imgQuestion,
                        answer: this.item.imgAnswer
                    }}
            />
        })

        return (
            {imgDataItem}            
        )
    }
}

我是新来的反应者,请在遇到问题时向我提供解决方案

1 个答案:

答案 0 :(得分:1)

尝试使用imgData的默认值分配destructuring

 render() {
    const {imgData = []} = this.state; 
    const imgDataItem = imgData.map(item => {
        <Jokes  data={{key: this.item.id}}
                data={{
                    img: this.item.imgName,
                    imgFileName: this.item.imgFile,
                    question: this.item.imgQuestion,
                    answer: this.item.imgAnswer
                }}
        />
    })

    return (
        {imgDataItem}            
    )
}