can someone explain the difference between
an anonymous function
<button onClick={() => this.functionNameHere()}></button>
and
calling the function like below
<button onClick={this.functionNameHere()}></button>
and also when to use either (such as different scenarios to use one over the other).
The first example correctly binds the value of this
(the exact problem lambdas strive to resolve in ES 2015).
() => this.functionNameHere()
The latter uses the scoped-value of this
which might not be what you expect it to be. For example:
export default class Album extends React.Component {
constructor(props) {
super(props);
}
componentDidMount () {
console.log(this.props.route.appState.tracks); // `this` is working
axios({
method: 'get',
url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
headers: {
'Authorization': 'JWT ' + sessionStorage.getItem('token')
}
}).then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}).catch(function (response) {
console.error(response);
//sweetAlert("Oops!", response.data, "error");
})
}
We would need to sub in a lambda here:
.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )
or bind manually:
.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}.bind(this) )
Examples stolen from: React this is undefined
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