'ReactJS - Same method, different results
I'm learning React and, while following a tutorial I wonder why the #1 method doesn't console.log anything, while the #2 one does. Can someone please explain why is that?
calculateFaceLocation = (data) => {
return (console.log(data.outputs[0].data.regions[0].region_info.bounding_box));
}
//DOESN'T WORK
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function (response) {
this.calculateFaceLocation(response);
}
)
}
//WORKS
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(response => this.calculateFaceLocation(response)).catch(err=> console.log(err));
}
Solution 1:[1]
In the #1 function, you give one regular function to .then(), so when it calls
this.calculateFaceLocation(response);
this object does not have that calculateFaceLocation() method which defines inside your react class, instead this object contains the window object.
But for your #2 function, you are using the arrow function which is why you are getting your console log value here. Because in the arrow function it does not have it's own this instead it's getting it from the parent.
Read more about Arrow Function
I have added console.log(this); inside both functions. Now run this code and check the console you will see the difference.
calculateFaceLocation = (data) => {
return (console.log(data.outputs[0].data.regions[0].region_info.bounding_box));
}
//DOESN'T WORK
onButtonSubmit = () => {
this.setState({ imageUrl: this.state.input })
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function (response) {
console.log(this);
this.calculateFaceLocation(response);
}
)
}
//WORKS
onButtonSubmit = () => {
this.setState({ imageUrl: this.state.input })
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
response => {
console.log(this);
this.calculateFaceLocation(response);
}
).catch(err => console.log(err));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SKG |
