未捕获的类型错误:this.state.data.map不是一个函数

Uncaught TypeError: this.state.data.map is not a function

本文关键字:函数 一个 map data 类型 错误 state this      更新时间:2023-09-26

我是React新手,见过一些类似的问题,但不知道为什么会发生这种情况。我得到一个"未捕获的类型错误:this.state.data.map不是一个函数"。下面是代码。请帮忙找出问题所在。

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>;
    }
}

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

this.state = {  data: [] };

.map不适用于String对象。考虑将'data'更改为数组。.map是对数组的每个元素调用函数的方法。

我在react-redux中也有同样的错误。

问题是当我在添加/产品页面添加新产品并点击后退按钮时,主页的组件显示此错误

home_container.js:8 Uncaught TypeError: products.product.map is not a function

renderItems = (products) => (
            products.product ? 
            products.product.map(item => (
                <ProductItem {...item} key = { item._id } />
            ))
            : null
        )

解决方案

我从节点服务器传递{}而不是[]

因此,当您在react-redux中遇到这种类型的错误时,请首先检查从服务器传递到该字段的内容,并检查该特定组件的reducer

首先必须将数据分割为一个数组,然后才能使用map函数。而不是

 this.state.data.map
使用

this.state.data.split('').map()

如果您的数据是字符串类型,那么您必须使用this.state.data.split('').map(ch=>{ console.log('Hello from map') })

我也遇到了同样的问题,但在我的情况下,这是因为在从控制器获取数据期间缺少JSON函数的括号。

fetch("https://localhost:44361/Api/Department").then(res=>res.json())
    .then(result => {
        this.setState({Departments:result});
    }
);