React js map()undefined不是一个函数

时间:2022-08-22 19:22:17

I am new to React and I am going a little crazy trying to figure out what I am doing wrong. I am trying to iterate through a json array that I get from an ajax call. When I mock the data it works perfectly, but when I make an ajax call to get the exact same data it gives me undefined is not a function (evaluating 'this.state.list.map()')

我是React的新手,我有点疯狂,想弄清楚我做错了什么。我试图遍历一个从ajax调用得到的json数组。当我模拟数据它完美地工作,但是当我进行ajax调用以获得完全相同的数据时,它给我undefined不是一个函数(评估'this.state.list.map()')

the array:

数组:

[ { "name": "drop1" }, { "name": "drop2" }, { "name": "drop3" } ]

[{“name”:“drop1”},{“name”:“drop2”},{“name”:“drop3”}]

the function:

功能:

var List = React.createClass({
  getInitialState: function() {
   return {data: {}};
 },
 componentDidMount: function() {
   $.ajax({
       url: ACTUAL_URL,
       dataType: 'json',
       success: function(data){
         this.setState({data: data});
       }.bind(this),
       error: function(xhr, status, err){
         console.error(url, status, err.toString());
       }.bind(this)
     });
  },
  render: function() {
    return (
      <ul className="droplist">
        {this.state.data.map(function(l){
           return (<li>{l.name}</li>)
        })}
      </ul>
    );
  }
});

Any help is much appreciated.

任何帮助深表感谢。

2 个解决方案

#1


15  

Change your getInitialState(). Currently your data is an object literal and object literals doesn't support map(). Change it to an array.

更改你的getInitialState()。目前,您的数据是对象文字,对象文字不支持map()。将其更改为数组。

#2


2  

In my case I was trying to use array.map but my data actually was an object rather than array so using Object.keys(data) is the right way to iterate over objects:

在我的情况下,我试图使用array.map,但我的数据实际上是一个对象而不是数组,所以使用Object.keys(数据)是迭代对象的正确方法:

Object.keys(data).forEach(item => {...});
// OR
Object.keys(data).map(item => {...});

Read details here

在这里阅读细节

#1


15  

Change your getInitialState(). Currently your data is an object literal and object literals doesn't support map(). Change it to an array.

更改你的getInitialState()。目前,您的数据是对象文字,对象文字不支持map()。将其更改为数组。

#2


2  

In my case I was trying to use array.map but my data actually was an object rather than array so using Object.keys(data) is the right way to iterate over objects:

在我的情况下,我试图使用array.map,但我的数据实际上是一个对象而不是数组,所以使用Object.keys(数据)是迭代对象的正确方法:

Object.keys(data).forEach(item => {...});
// OR
Object.keys(data).map(item => {...});

Read details here

在这里阅读细节