从 reactjs 教程中,.bind(this)在 ajax 回调结束时有什么目的?没有它,代码能正常工作吗?
data: JSON.stringify({text: text}),
success: function (data) {
this.setState({data: data});
}.bind(this),
从 reactjs 教程中,.bind(this)在 ajax 回调结束时有什么目的?没有它,代码能正常工作吗?
data: JSON.stringify({text: text}),
success: function (data) {
this.setState({data: data});
}.bind(this),
它确保this将是回调中的正确对象。参见Function.prototype.bind()。
特定于react的替代方法是执行以下操作:
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在回调中的位置。
.bind(this)在 ajax 回调结束时的目的是让this与您的react类相关。换句话说,您可以添加:
var self = this;
在 ajax 之外,它的工作原理相同。你的代码等于:
var self = this;
$.ajax({
.
.
data: JSON.stringify({text: text}),
success: function (data) {
self.setState({data: data});
},
.
.
});