ajax回调结束时.bind(this)的目的? [英] purpose of .bind(this) at end of ajax callback?
问题描述
在reactjs教程中,在ajax回调的末尾具有 .bind(this)
的目的是什么?没有它,代码是否可以正常工作?
From the reactjs tutorial, what's the purpose of having .bind(this)
at the end of the ajax callback? Does code work correctly without it?
data: JSON.stringify({text: text}),
success: function (data) {
this.setState({data: data});
}.bind(this),
推荐答案
确保 this
将是回调内的正确对象.参见 Function.prototype.bind().
It ensure's this
will be the correct object inside the callback. See Function.prototype.bind().
特定于反应的替代方法是:
An alternative specific to react is to do:
myAjaxFunction: function(){
$.getJSON('/something', this.handleData);
},
handleData: function(data){
this.setState({data: data});
}
之所以有效,是因为React为您处理了组件方法的绑定.
This works because React handles binding of component methods for you.
如果在没有绑定的情况下运行原始代码,则会出现以下错误: TypeError:undefined不是一个函数
,因为回调中的 this === window
;
If you ran your original code in without bind, you'd get this error: TypeError: undefined is not a function
because this === window
in the callback;
或在严格模式下: TypeError:无法读取未定义属性'setState'
,其中在回调中 this === undefined
.
or in strict mode: TypeError: Cannot read property 'setState' of undefined
, where this === undefined
in the callback.
这篇关于ajax回调结束时.bind(this)的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!