我有以下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>
);
}
});
而且在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>
);
}
});
在getInitialState()
,我已经对数据和赋值CommentList
也添加从状态获得值的属性数据。
当我尝试运行,我得到这个错误:
Cannot read property 'map' of undefined in CommentList.
你是否改变了componentDidMount的状态?你确定它在第一次渲染失败吗?我在第一次渲染中看不到任何可能出错的情况,getInitialState在第一次渲染之前运行 –
是的,我通过从服务器通过ajax加载数据来更改componentDicMount上的状态。 –
您的代码有效,请在此处查看。 https://jsfiddle.net/4vaq7mL7/1/向我显示componentDidMount上的代码 –