Wednesday 25 December 2019

javascript - the meaning of 'this' in componentDidMount(), ReactJS




Seeking clarification on the meaning of 'this' in this context. Why do I need to bind 'this' to the callback after the ajax request? When I check the debugger, it says 'this' is bound to the constructor whether I call bind or not.



var BugList = React.createClass({
getInitialState: function() {
return {
bugs: []
}
},


componentDidMount: function() {

$.ajax('/api/bugs').done(function(data) {
this.setState({
bugs: JSON.parse(data)
});
}.bind(this));
},

Answer




That is because this by default this will point to the:




value of the ThisBinding of the current execution context;




Since your context will change during the time the callback actually runs, this will not refer to your current instance of BugList.



The .bind(this) essentially declares that no matter the context, set this to mean the context of where this function has been created (ie. BugList)




I'd recommend you look at: Standard ECMA-262, and Scopes in JS. For a more detailed explanation about this concept!


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...