小编典典

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

reactjs

在reactjs教程中,.bind(this)在ajax回调的末尾有什么用途?没有它,代码是否可以正常工作?

        data: JSON.stringify({text: text}),
        success: function (data) {
            this.setState({data: data});
        }.bind(this),

阅读 416

收藏
2020-07-22

共1个答案

小编典典

确保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 undefinedthis === undefined位于回调中。

2020-07-22