React tutorial - why bind this when calling ajax

Now I am doing a React tutorial and wondering how to bind to an ajax call. Why do we bind this for success and error in ajax call? Apparently, when I removed the binding, the function throws an error. Do we use binding because we have this.setState in the function and we need the right link?

  // tutorial13.js var CommentBox = React.createClass({ getInitialState: function() { return {data: []}; }, componentDidMount: function() { $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, render: function() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data} /> <CommentForm /> </div> ); } }); 
+8
jquery reactjs
source share
3 answers

this refers to the object that calls the function. bind first argument is the value of this . Thus, function(data){...}.bind(an_object) can be read as "call this function, but set this inside the function to refer to an_object ". In the case of the React tutorial, an_object refers to the React component. So:

  success: function(data) { this.setState({data: data}); } 

this refers to an AJAX object. console.log(this) gives us

 Object {url: "comments.json", type: "GET", isLocal: false, global: true, processData: true…} 

  success: function(data) { this.setState({data: data}); }.bind(this) 

this refers to the React component. console.log(this) gives us

 ReactCompositeComponent.createClass.Constructor {props: Object, _owner: null, _lifeCycleState: "MOUNTED", _pendingCallbacks: null, _currentElement: ReactElement…} 

For further reading, Nicholas Zakas' book Object-Oriented Javascript explains in detail how bind works.

+12
source share

Statement is equivalent

 componentDidMount: function() { var me = this; $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { me.setState({data: data}); } }); } 
+4
source share

Oh, I get it! After using the dev tool to validate, "this" references ReactClass.createClass.Constructor . Therefore, the reason to associate this with the success and error of the ajax call is to make sure that we have the right to "this" when we call this.setState({data:data}); or console.error(this.props.url, status, err.toString());

If we do not bind "this". we lost the correct React "this", and "this" can turn into a window, jQuery or other thing at any time. The reason we got the error "Uncaught TypeError: undefined is not a function".

+2
source share