反应:无法读取未定义的属性“数据”
2016-10-12
9110
我正在从文档中学习 reactjs。当我传输通过状态传递的数据时。例如。
getInitialState()
我收到错误:
Cannot read property 'data' of undefined
我尝试将
getInitialState()
更改为
this.state = { data : []
。但是这不是正确的方法。我该如何修复它?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello React</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script>
<script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xpa1/t39.3284-6/11057105_1610731242494235_1148661094_n.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
//Comment text
let converter = new Showdown.converter();
let Comment = React.createClass({
render(){
let rawMarkup = converter.makeHtml(this.props.children.toString())
return (
<div className="comment">
<h2 className="commentAuthor">
{ this.props.author }
</h2>
<span dangerouslySetInnerHTML={{__html: rawMarkup}}/>
</div>
);
}
});
//Comment list
let CommentList = React.createClass({
render(){
let commentNodes = this.props.data.map((comment, index) => {
return (
<Comment author={comment.author} key={index}>
{ comment.text }
</Comment>
)
});
return (
<div className="commentList">
{ commentNodes }
</div>
);
}
});
//Comment form
let CommentForm = React.createClass({
render(){
return (
<div className="commentForm">
CommentForm !!
</div>
);
}
});
//Comment component
let CommentBox = React.createClass({
getInitialState(){
return {
data: [
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"}
]
}
},
render(){
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={ this.state.data }/>
<CommentForm />
</div>
);
}
});
React.render(
<CommentBox data={this.state.data}/>, //<----[ERROR IS HERE Uncaught TypeError]
document.getElementById('content')
);
</script>
</body>
</html>
1个回答
状态由组件独立处理。您正尝试在 React 组件 外部 访问状态。您传递了 { this.state.data } 作为 prop,但您根本不需要该 prop。您应该能够完全删除数据 prop,您的代码将正常工作。
<CommentBox /> // 删除数据 prop
Nick Tucci
2016-10-12