.bind(this)在ajax回调结束时的目的?

fer*_*k86 58 ajax reactjs

在reactjs教程中,.bind(this)在ajax回调结束时有什么目的?没有它,代码是否正常工作?

        data: JSON.stringify({text: text}),
        success: function (data) {
            this.setState({data: data});
        }.bind(this),
Run Code Online (Sandbox Code Playgroud)

Bri*_*and 57

它确保this它将成为回调中的正确对象.请参见Function.prototype.bind().

反应的另一个具体方法是:

myAjaxFunction: function(){
  $.getJSON('/something', this.handleData);
},
handleData: function(data){
  this.setState({data: data});
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为React为您处理组件方法的绑定.

如果您在没有绑定的情况下运行原始代码,则会收到此错误:TypeError: undefined is not a function因为this === window在回调中;

或者在严格模式下:TypeError: Cannot read property 'setState' of undefined,this === undefined在回调中的位置.

  • 还找到了这篇方便的文章,解释了绑定,应用和调用方法的用例 - http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ (4认同)