在reactjs教程中,.bind(this)在ajax回调的末尾有什么用途?没有它,代码是否可以正常工作?
.bind(this)
data: JSON.stringify({text: text}), success: function (data) { this.setState({data: data}); }.bind(this),
确保this回调中的对象正确。参见Function.prototype.bind()。
this
特定于反应的替代方法是:
myAjaxFunction: function(){ $.getJSON('/something', this.handleData); }, handleData: function(data){ this.setState({data: data}); }
之所以行之有效,是因为React为您处理了组件方法的绑定。
如果你在没有绑定跑你的原代码,你会得到这个错误:TypeError: undefined is not a function因为this === window在回调;
TypeError: undefined is not a function
this === window
或在严格模式下:TypeError: Cannot read property 'setState' of undefined,this === undefined位于回调中。
TypeError: Cannot read property 'setState' of undefined
this === undefined