[英]React js map() undefined is not a function
I am new to React and I am going a little crazy trying to figure out what I am doing wrong. 我是React的新手,我有点疯狂试图找出我做错了什么。 I am trying to iterate through a json array that I get from an ajax call.
我试图迭代我从ajax调用得到的json数组。 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()')
当我模拟数据时,它工作得很好,但当我进行ajax调用以获得完全相同的数据时,它给我的
undefined is not a function (evaluating 'this.state.list.map()')
the array: 数组:
[ { "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. 任何帮助深表感谢。
Change your getInitialState()
. 更改你的
getInitialState()
。 Currently your data is an object literal and object literals doesn't support map()
. 目前,您的数据是对象文字,对象文字不支持
map()
。 Change it to an array. 将其更改为数组。
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(data)
是迭代对象的正确方法:
Object.keys(data).forEach(item => {...});
// OR
Object.keys(data).map(item => {...});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.