开发者问题收集

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

2014-07-11
553336

我正在按照 reactjs 教程操作,在
将值从一个组件的状态传递到另一个组件 时,我总是遇到问题。

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

What would cause the prop to be undefined when passing from CommentBox into the CommentList ?

// 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'));
3个回答

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

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>
      );
  });
}

taggon
2014-07-11

我认为您忘记在 CommentBox 的渲染函数中将

data={this.props.data}

更改为

data={this.state.data}

。我在按照教程操作时也犯了同样的错误。因此整个渲染函数应为

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.state.data} />
      <CommentForm />
    </div>
  );
}

,而不是

render: function() {
  return (
    <div className="commentBox">
      <h1>Comments</h1>
      <CommentList data={this.props.data} />
      <CommentForm />
    </div>
  );
finrod
2015-10-11

您需要在渲染之前放置数据

应该是这样的:

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

而不是这样:

React.render(
  <CommentBox data={data}/>,
  document.getElementById('content')
);

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];
Liliang Zhu
2015-12-15