我现在正在做 React 教程,想知道 ajax 调用中的绑定(bind)。为什么我们需要在ajax调用中绑定(bind)这个来表示成功和错误?显然,当我删除绑定(bind)时,该函数会抛出错误。我们是否使用绑定(bind),因为函数中有 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>
);
}
});
最佳答案
this
指的是调用该函数的对象。 bind
的第一个参数是 this
的值。所以 function(data){...}.bind(an_object)
可以读作“调用这个函数,但是在函数内部设置 this
来引用an_object
”。在 React 教程中,an_object
指的是 React 组件。所以:
success: function(data) {
this.setState({data: data});
}
this
指的是 AJAX 对象。 console.log(this)
给我们
Object {url: "comments.json", type: "GET", isLocal: false, global: true, processData: true…}
<小时/>
success: function(data) {
this.setState({data: data});
}.bind(this)
this
指的是 React 组件。 console.log(this)
给我们提供了
ReactCompositeComponent.createClass.Constructor {props: Object, _owner: null, _lifeCycleState: "MOUNTED", _pendingCallbacks: null, _currentElement: ReactElement…}
如需进一步阅读,Nicholas Zakas 的书 Object Oriented Javascript详细解释了 bind
的工作原理。
关于jquery - React 教程 - 为什么在 ajax 调用中绑定(bind)它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452772/