purpose of .bind(this) at end of ajax callback?

后端 未结 2 549
离开以前
离开以前 2021-01-30 04:07

From the reactjs tutorial, what\'s the purpose of having .bind(this) at the end of the ajax callback? Does code work correctly without it?

        d         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 04:40

    It ensure's this will be the correct object inside the callback. See Function.prototype.bind().

    An alternative specific to react is to do:

    myAjaxFunction: function(){
      $.getJSON('/something', this.handleData);
    },
    handleData: function(data){
      this.setState({data: data});
    }
    

    This works because React handles binding of component methods for you.

    If you ran your original code in without bind, you'd get this error: TypeError: undefined is not a function because this === window in the callback;

    or in strict mode: TypeError: Cannot read property 'setState' of undefined, where this === undefined in the callback.

提交回复
热议问题