李明泽 李明泽 - 1 month ago 6
Javascript Question

react:Cannot read property 'data' of undefined

i'm study reactjs from the document.when i transmit the data passed by state.
eg. "getInitialState()",
but the error "Cannot read property 'data' of undefined" appear.

I try to change getInitialState() to this.state = { data : []}.however this is not right way.
how could i fix it.thanks!



<!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>




Answer

The states are handled independently by the components. You are trying to access the state outside of a React component. You are passing { this.state.data } as a prop when you don't need the prop in the first place. You should be able to remove the data prop entirely and your code will work just fine.

<CommentBox /> // get rid of data prop

Comments