I have the following ReactJS code:
我有以下ReactJS代码:
var CommentList = React.createClass({
render: function(){
var commentNodes = this.props.data.map(function(comment){
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
And in CommentBox....
并在CommentBox ....
var CommentBox = React.createClass({
loadCommentFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
data: data
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
},
getInitialState: function() {
return {
data: []
};
},
componentDidMount: function() {
this.loadCommentFromServer();
setInterval(this.loadCommentFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className = "commentBox" >
<h1> Comments </h1>
<CommentList data ={ this.state.data } />
<CommentForm />
</div>
);
}
});
In getInitialState()
, I already assign value for data and in CommentList
also add property data which get value from state.
在getInitialState()中,我已经为数据赋值,在CommentList中还添加了从state获取值的属性数据。
When I try to run, I got this error:
当我尝试运行时,我收到此错误:
Cannot read property 'map' of undefined in CommentList.
无法读取CommentList中未定义的属性“map”。
1 个解决方案
#1
0
It looks like you simply aren't getting the data you want back from the jQuery.ajax.
看起来你根本就没有从jQuery.ajax获取你想要的数据。
success: function(data) {
// before setting state, log here and find out what data is
// it could need to be turned into JSON? data = data.toJSON();
// or simply this to be safe
data = data || [];
this.setState({
data: data
});
}
#1
0
It looks like you simply aren't getting the data you want back from the jQuery.ajax.
看起来你根本就没有从jQuery.ajax获取你想要的数据。
success: function(data) {
// before setting state, log here and find out what data is
// it could need to be turned into JSON? data = data.toJSON();
// or simply this to be safe
data = data || [];
this.setState({
data: data
});
}