As I am following an example in React’s documentation on using this.setState
to toggle an on/off button.
I am experimenting with non-arrow functions in this.setState but have difficulty understanding why non-arrow functions wouldn’t work, or if something needs to be added to a non-arrow function to make it work.
This is the official code snippet:
this.setState( prevState => ({ isToggleOn: !prevState.isToggleOn})); }
However, the button failed to change from “on” to “off” when rewrote the arrow function as a regular function.
this.setState( function(prevState) { isToggleOn : !prevState.isToggleOn;} ); }
I’ve tried adding the return
keyword before isToggleOn
, but it didn’t work.
I’m guessing it has something to do with the difference of scoping and this
between an arrow function and a regular function. Am I missing something here?
Here is the source of the React documentation.
Advertisement
Answer
Arrow functions are purely syntax sugar and can always be rewritten using ordinary function
.
this.setState( prevState => ({ isToggleOn: !prevState.isToggleOn}) )
this
doesn’t appear inside the function so that’s not the issue.
What you wrote –
this.setState( function(prevState) { isToggleOn : !prevState.isToggleOn; // ^__ missing `return`, missing enclosing object {...} } )
What you meant to write –
this.setState( function(prevState) { return { isToggleOn : !prevState.isToggleOn } } )