无法读取未定义的属性“地图”

reactjs React.js

米亚

2020-04-03

我正在按照本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'));

第3976篇《无法读取未定义的属性“地图”》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Gil伽罗小宇宙 2020.04.03

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

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>
      );
  });
}
西里Near 2020.04.03

我想你忘了改变

data={this.props.data}

data={this.state.data}

在CommentBox的渲染功能中。在遵循本教程时,我犯了同样的错误。因此,整个渲染函数应该看起来像

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android