<分区>
我正在关注 React Beginner Tutorial我正在尝试将其翻译成 ES6。但是,当我将 CommentBox
更改为 ES6 类时,它开始给我一个 this.props.url
is undefined
错误(在 AJAX 调用中loadCommentsFromServer
)。我认为这与 ES6 如何绑定(bind) this
有关,但我对这门语言(也不是 React)不是很熟悉,所以我不确定。我看过 React 0.13 release notes并看到了这个:
React.createClass has a built-in magic feature that bound all methods to
this
automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.
我不太确定,但我认为这意味着我必须保存 this 的值(如 let that = this
和 .bind(that)
) 但这也给出了相同的 this.props.url
is undefined
- 我不确定下一步要去哪里。
这是我当前的代码:
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>
);
}
};