未捕获的TypeError:this.state.data.map不是函数 [英] Uncaught TypeError: this.state.data.map is not a function

查看:118
本文介绍了未捕获的TypeError:this.state.data.map不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React的新手,看过一些类似的问题,但没有找到为什么会这样。我得到一个未捕获的TypeError:this.state.data.map不是一个函数。
这是代码。请帮助找出问题所在。

I am new to React, have seen some of the similar issues, but didn’t find why this happens. I am getting an "Uncaught TypeError: this.state.data.map is not a function". Here is the code. Please, help to find what is the problem.

class Audienses extends React.Component {

    constructor (props)
    {
        super(props);

        this.state = {
            data: ''
        };

        this.loadFromServer = this.loadFromServer.bind(this);
        this.childeDelete = this.childeDelete.bind(this);
        this.childeEdit = this.childeEdit.bind(this);

    }

    loadFromServer () {
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
            var data = JSON.parse(xhr.responseText);
            this.setState({ data: data });

        }.bind(this);
        xhr.send();
    }

    componentDidMount() {
        this.loadFromServer();   
    }


     render () {

         var audienses = this.state.data.map((value, index) => (
           <OneElement key={value.id} audience={value.audience} description={value.description} />
        ));

        /* or like this
         var audienses = this.state.data.map(function(s) {
             <OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} />
         }).bind(this);
        */
         return
        <div>
            <h1>Audiences</h1>
            <table id="services">
                <tr>
                    <th>Audience</th>
                    <th>Description</th>
                    <th></th>
                    <th></th>
                </tr>
                <tbody>
                   {audienses}
                </tbody>
            </table>
        </div>;
    }
}


推荐答案

您的initial data state is String 。, String 没有方法 .map ,您需要将初始状态''更改为 [ ]

Your initial data state is String., String does not have method .map, you need change your initial state from '' to []

this.state = {  data: [] };

这篇关于未捕获的TypeError:this.state.data.map不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆