最佳答案
我正在学习 reactjs
教程,当 < br/> 将值从一个组件的状态传递到另一个组件. < br/> 时,我不断遇到一个问题
错误 Cannot read property 'map' of undefined'
在执行 CommentList
组件中的 map
函数时引发。
当从
CommentBox
传递到CommentList
时,是什么使得prop
成为undefined
?
// First component
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function (comment){
return <div><h1>{comment.author}</h1></div>;
});
return <div className="commentList">{commentNodes}</div>;
}
});
// Second component
var CommentBox = React.createClass({
getInitialState: function(){
return {data: []};
},
getComments: function(){
$.ajax({
url: this.props.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)
});
},
componentWillMount: function(){
this.getComments()
},
render: function(){
return <div className="commentBox">{<CommentList data={this.state.data.comments}/>}</div>;
}
});
React.renderComponent( <CommentBox url="comments.json" />, document.getElementById('content'));