在reactjs教程中,.bind(this)
在ajax回调结束时有什么目的?没有它,代码是否正常工作?
data: JSON.stringify({text: text}), success: function (data) { this.setState({data: data}); }.bind(this),
Brigand.. 57
它确保this
它将成为回调中的正确对象.请参见Function.prototype.bind().
反应的另一个具体方法是:
myAjaxFunction: function(){ $.getJSON('/something', this.handleData); }, handleData: function(data){ this.setState({data: data}); }
这是有效的,因为React为您处理组件方法的绑定.
如果您在没有绑定的情况下运行原始代码,则会收到此错误:TypeError: undefined is not a function
因为this === window
在回调中;
或者在严格模式下:TypeError: Cannot read property 'setState' of undefined
,this === undefined
在回调中的位置.
它确保this
它将成为回调中的正确对象.请参见Function.prototype.bind().
反应的另一个具体方法是:
myAjaxFunction: function(){ $.getJSON('/something', this.handleData); }, handleData: function(data){ this.setState({data: data}); }
这是有效的,因为React为您处理组件方法的绑定.
如果您在没有绑定的情况下运行原始代码,则会收到此错误:TypeError: undefined is not a function
因为this === window
在回调中;
或者在严格模式下:TypeError: Cannot read property 'setState' of undefined
,this === undefined
在回调中的位置.