gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:06:49 24 4
gpt4 key购买 nike

在学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com