Honestly, this is my day 1 in ReactJS. I'm learning some small-small things like state
. I've created a small program for the toggle button. It will simply display "Hello world!" or display nothing when the button is toggled. There's one thing that I didn't understand. My code gives me an error when I use this syntax:
toggleHandler() {
const currentStatus=this.state.display;
this.setState({
display: !currentStatus
})
}
this.state is undefined
But the same code works perfectly If I change the syntax to a fat arrow function:
toggleHandler=()=> {
const currentStatus=this.state.display;
this.setState({
display: !currentStatus
})
}
I'll not waste your time. I've created an stackblitz. Experts on the internet say that any call to this.setState()
is asynchronous. So I tried using call back function
and IIFE
but got myself more confused and over-complicated. Please correct me. I'm sorry this is a very childish question.