javascript React js map() undefined 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28463807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React js map() undefined is not a function
提问by this_is_ender
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 is not a function (evaluating '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.
任何帮助深表感谢。
回答by Henrik Andersson
Change your getInitialState().
Currently your data is an object literal and object literals doesn't support map().
Change it to an array.
改变你的getInitialState(). 目前您的数据是对象文字,对象文字不支持map(). 将其更改为数组。
回答by adi
In my case I was trying to use array.mapbut 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 => {...});

