Why do event handlers need to bind with the constructor while render and other methods do not require the same in react?
You may see here in the below code that for handlesubmit I need to bind it with the constructor but I don't need to do the same with api method. Can someone explain to me the reason behind it?
Thank you
class App extends Component{
constructor (props){
super(props);
this.state={
users:[],
loading:false
};
this.handleSubmit = this.handleSubmit.bind(this);
}
api(){
this.setState({
loading: true
})
axios('https://api.randomuser.me/')
.then(respond => this.setState({
users: [...this.state.users, ...respond.data.results],
loading: false
}))
}
handleSubmit(e){
e.preventDefault();
this.api();
}
UNSAFE_componentWillMount(){
this.api();
}
render(){
let {loading,users} = this.state;
console.log("run")
return <div className = "App">
<form onSubmit = {this.handleSubmit}>
<input type="submit" value= "Refresh" />
</form>
{!loading
? (users.map( user =>
<div key = {user.id.value}>
<h2> {user.name.first} </h2>
<p>{user.email}</p>
</div>
)) : (<Loading/>)}
</div>;
}
}
export default App;