ReactJS 失败并出现错误 "Cannot read property ' map' of undefined`”

标签 reactjs

在学习 React.js 教程后,我遇到了一个错误:未捕获的类型错误:无法读取未定义的属性“map”

我正在关注the tutorial严格但停留在从服务器获取部分。当我向 commentBox 提供 url 数据而不是硬编码的 JSON 数据时,会出现错误。

/** @jsx React.DOM */

var converter = new Showdown.converter();

var data = [
  { Author: "Daniel Lo Nigro", Text: "Hello ReactJS.NET World!" },
  { Author: "Pete Hunt", Text: "This is one comment" },
  { Author: "Jordan Walke", Text: "This is *another* comment" }
];

var Comment = React.createClass({
  render: function() {
  var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: function() {

    var commentNodes = this.props.data.map(function (comment) {
      return <Comment author={comment.Author}>{comment.Text}</Comment>;
    });

    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

var CommentForm = React.createClass({
  render: function() {
    return (
      <div className="commentForm">
        Hello, world! I am a CommentForm.
      </div>
    );
  }
});

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>

        <CommentList data={this.props.data} />

        <CommentForm />
      </div>
    );
  }
});

React.renderComponent(
  //<CommentBox data={data}/>,            //this works fine
  <CommentBox url="/comments" />,         //Changing data feet to url produces an error
  document.getElementById('content')
);

http://localhost:52581/comments 上的请求正在运行并返回 JSON 数据:

[{"Author":"Daniel Lo Nigro","Text":"Hello ReactJS.NET World!"},{"Author":"Pete Hunt","Text":"This is one comment"},{"Author":"Jordan Walke","Text":"This is *another* comment"}]

任何建议都会对我有很大帮助。谢谢。

最佳答案

在 CommentBox 中,这一行就是问题所在:<CommentList data={this.props.data} />

您不再拥有props.data因为您传递的是 URL 而不是 JS 对象。

你的第二个是有效的,因为你使用状态并将值默认为空数组,它仍然可以在其上运行 map 。

关于ReactJS 失败并出现错误 "Cannot read property ' map' of undefined`”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24776540/

相关文章:

javascript - React Native 在 setState 之后不重新渲染

reactjs - 在我的案例中执行 React Router 历史推送时如何滚动到页面

javascript - React.useMemo 无法防止重新渲染

javascript - 将 "Route children"和 "cloneElement"转换为 RouterV4

reactjs - React bulma 组件导入不起作用

javascript - 井字游戏教程 : How can I trigger multiple callback functions?

javascript - React 组件不刷新或重新渲染

android - 为什么 ReactNative Dimensions 组件报告分辨率降低?

javascript - 更改纸张颜色 Material-UI

reactjs - FCM(Firebase 云消息): Firebase push notifications are displayed in Firefox but not in Chrome