我正在研究文件中的reactjs。当我传输状态传递的数据时。例如。 getInitialState()
我收到错误:
无法读取未定义的属性“数据”
我尝试将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>
答案 0 :(得分:2)
状态由组件独立处理。您正尝试访问React组件的外部状态。当你首先不需要道具时,你正在传递{this.state.data}作为道具。您应该能够完全删除数据道具,并且您的代码可以正常工作。
<CommentBox /> // get rid of data prop