我现在正在做 React 教程,并想知道 ajax 调用中的绑定。为什么我们需要在 ajax 调用中为成功和错误绑定 this?显然,当我删除绑定时,该函数会抛出错误。我们使用绑定是因为我们this.setState
在函数中需要一个正确的引用吗?
// tutorial13.js
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
});