Warm tip: This article is reproduced from serverfault.com, please click

reactjs-错误:无法读取未定义的属性“ map”

(reactjs - Error : Cannot read property 'map' of undefined)

发布于 2014-07-11 20:44:48

我正在学习reactjs教程,并且在
将值从一个组件的状态传递到另一个组件时一直遇到问题

执行组件中Cannot read property 'map' of undefined'map函数时抛出错误CommentList

什么会导致的propundefined从路过的时候CommentBoxCommentList

// 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'));
Questioner
Nael
Viewed
0
taggon 2014-07-12 08:47:26

首先,设置更安全的初始数据:

getInitialState : function() {
    return {data: {comments:[]}};
},

并确保你的ajax数据。

如果你按照上面的两个说明(例如Demo)进行操作,它应该可以工作

更新:你可以使用条件语句包装 .map 块。

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}