在react.js教程之后,我遇到了一个错误:Uncaught TypeError: Cannot read property 'map' of undefined。
Uncaught TypeError: Cannot read property 'map' of undefined
我严格按照本教程进行操作,但停留在 从服务器 部分进行 访存 。当我用URL数据而不是硬编码的JSON数据给commentBox喂消息时,会出现错误。
/ ** @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资料:
http://localhost:52581/comments
[{"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} />
<CommentList data={this.props.data} />
您不再需要,props.data因为您传入的是URL而不是JS对象。
props.data
您的第二个作品之所以有效,是因为您使用state并将默认值设置为一个空数组,但仍可以在其上运行map。