The .bind (this) target at the end of the ajax callback?

From the response tutorial, what is the purpose of .bind(this) at the end of the ajax callback? Does the code work correctly without it?

  data: JSON.stringify({text: text}), success: function (data) { this.setState({data: data}); }.bind(this), 
+58
ajax reactjs
Jun 18 '14 at 12:26
source share
3 answers

This ensures that this will be the correct object inside the callback. See Function.prototype.bind () .

An alternative to responding is:

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

This works because React handles component method bindings for you.

If you run your source code without binding, you will 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.

+57
Jun 18 '14 at 13:03
source share

Assigning .bind(this) at the end of the ajax callback allows this be associated with your response class. In other words, you can add:

 var self = this; 

outside ajax and it works the same way. You code is equal to:

 var self = this; $.ajax({ . . data: JSON.stringify({text: text}), success: function (data) { self.setState({data: data}); }, . . }); 
+2
Mar 19 '17 at 8:08
source share

An updated answer in 2019, we can choose to use bind(this) or not at present.

1) In the traditional way, we can use bind(this) in the constructor, so when we use the function as a JSX callback, the context of this is the class itself.

 class App1 extends React.Component { constructor(props) { super(props); // If we comment out the following line, // we will get run time error said 'this' is undefined. this.changeColor = this.changeColor.bind(this); } changeColor(e) { e.currentTarget.style.backgroundColor = "#00FF00"; console.log(this.props); } render() { return ( <div> <button onClick={this.changeColor}> button</button> </div> ); } } 

2) If we define a function as an attribute / field of a class, we no longer need to use bind(this) .

 class App2 extends React.Component { changeColor = e => { e.currentTarget.style.backgroundColor = "#00FF00"; console.log(this.props); }; render() { return ( <div> <button onClick={this.changeColor}> button 1</button> </div> ); } } 

3) If we use the arrow function as a JSX callback, we also do not need to use bind(this) . And even more, we can pass parameters. It looks good, doesn't it? but its flaw is a performance issue, see ReactJS for details .

 class App3 extends React.Component { changeColor(e, colorHex) { e.currentTarget.style.backgroundColor = colorHex; console.log(this.props); } render() { return ( <div> <button onClick={e => this.changeColor(e, "#ff0000")}> button 1</button> </div> ); } } 

And I created Codepen to demonstrate these code snippets, hope this helps.

0
Jun 28 '19 at 0:38
source share



All Articles