我正在按照本reactjs教程进行操作,并且在 将值从一个组件的状态传递到另一个组件 时遇到了一个问题。
reactjs
Cannot read property 'map' of undefined' 当执行组件中的map功能时,将引发错误CommentList。
Cannot read property 'map' of undefined'
map
CommentList
什么会导致的prop是undefined从路过的时候CommentBox到CommentList?
prop
undefined
CommentBox
// 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'));
首先,设置更安全的初始数据:
getInitialState : function() { return {data: {comments:[]}}; },
并确保您的ajax数据。
如果您按照上面的两个指示(如“ 演示”)操作,它应该可以工作。
更新:您可以仅使用条件语句包装.map块。
if (this.props.data) { var commentNodes = this.props.data.map(function (comment){ return ( <div> <h1>{comment.author}</h1> </div> ); }); }