I'm doing React tutorial now, and wondering the binding in ajax call. Why do we need to bind this for success and error in the ajax call? Apparently when I removed binding, the function will throw an error. Do we use binding because we have this.setState
in the function and need a right reference?
// 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>
);
}
});
ReactJS bind() Method The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax: this. function.
ReactJS – bind() method React has a predefined bind() method which we can use to pass the arguments to a function in the class based components.
In ReactJS, we need to bind events so that the this keyword would not return an “undefined“. In this article, we are going to see the different ways in which we can bind event handlers in ReactJS.
To avoid the need for binding we have something introduced in ES6 as arrow functions. Using the arrow function to call this. setState will lead to avoid the use of bind.
this
refers to the object that called the function. bind
's first argument is the value of this
. So 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 the 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's book Object Oriented Javascript explains in detail how bind
works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With