我正在关注 React 教程:http://facebook.github.io/react/docs/tutorial.html
我只是之后 http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server
我在 SO 上经历了类似的问题,但没有找到适合我的具体案例的解决方案。
var data = [
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"},
{author: "Bob Lilly", text: "This is *another* comment 2"}
];
var Comment = React.createClass({
render: function() {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
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">
<br/>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.render(
// <CommentBox url="comments.json" />,
<CommentBox data={data} />,
document.getElementById('content')
);
当我尝试使用从服务器获取的数据时(第一步 --> 参见第二个链接),我收到此错误:
Uncaught TypeError: Cannot read property 'data' of null
我猜这与以错误的方式传递数据有关。
编辑:我用目前给出的答案编辑了鳕鱼
编辑 2:现在它可以处理哑数据(var data = [ ...),但不能处理从服务器获取的数据
最佳答案
您正在将 data
作为 prop 发送到 CommentBox
并尝试通过 CommentBox
状态传递它。
<CommentList data={this.props.data} />
代替
<CommentList data={this.state.data} />
我通常这样推理 Prop ; Props 是即将到来的东西,State 是已经存在的东西。
关于javascript - react 教程 : Uncaught TypeError: Cannot read property 'data' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489741/