I am following the React Beginner Tutorial and I am trying to convert it to ES6. However, when I changed CommentBoxto the ES6 class, he began to give me the error this.props.urlis undefined(in an AJAX call in loadCommentsFromServer). I think this is due to the way ES6 connects this, but I'm not very familiar with the language (or React), so I'm not sure. I looked at the React 0.13 release and saw this:
React.createClass has a built-in magic function that automatically binds all methods to thisyou. This can be a bit confusing for JavaScript developers who are not used for this function in other classes, or it can be confusing when they move from React to other classes.
I'm not quite sure, but I thought it meant that I needed to keep the meaning of this (as in let that = thisand .bind(that)), but it also gave the same this.props.urlis undefined- I'm not sure where to go next.
Here is my current code:
class CommentBox extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
loadCommentsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({
data: data
})
}.bind(this)
});
}
handleCommentSubmit(comment) {
var comments = this.state.data;
var newComments = comments.concat([comment]);
this.setState({ data: newComments });
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({ data: data });
},
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data}/>
<CommentForm onCommentSubmit={this.handleCommentSubmit}/>
</div>
);
}
};
source
share