I am learning ReactJS and I have seen many available answers but I am unable to understand that why this.setStateHandler = this.setStateHandler.bind(this);
is being used in the code given below? Why we cannot simply call the setStateHandler
function on button click without this code of line written in the constructor (as we normally do in other programming languages)? Please explain in simple terminology.
Code
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
this.setStateHandler = this.setStateHandler.bind(this);
};
setStateHandler() {
var item = "setState..."
var myArray = this.state.data;
myArray.push(item)
this.setState({data: myArray})
};
render() {
return (
<div>
<button onClick = {this.setStateHandler}>SET STATE</button>
<h4>State Array: {this.state.data}</h4>
</div>
);
}
}
export default App;