React arrow function produced different debugging experience
React arrow function produced different debugging experience
I am currently working on a react UI project, and involves lots of debugging with browsers. The strange thing is that when I do not use arrow function on button click event, the browser debugger shows this.state as undefined when mouse over it. When I use arrow function
() => this.alert()
the debugger console shows the correct state when mouse over and both these logging correct output when I do console.log(). Also I tested this behavior in Chrome and it is same as FF.
Any one has any idea will be much appreciated, since this brings really big issue when debugging without seeing the state, and it is not realistic to console.log for every state change.
Could not show this.state when mouse over it
Can show this.state when mouse over
@Think-Twice, onClick=() => this.alert will not work, either you use onClient=() => this.alert(), or totally no bracket
– Xiaoliang Sha
Aug 26 at 13:14
Hoo okey got it.
– Think-Twice
Aug 26 at 13:25
1 Answer
1
Please note that when you do:
somehandler = () => ...
in your component, it's already bound to the component instance, i.e. this = your component instance
, so you don't need to do onClick=() => this.somehandler()
, which binds it yet again to the component instance.
this = your component instance
onClick=() => this.somehandler()
Stick to the former and you'll be good to go!
Edit: I now realize that it's actually onClick=this.somehandler
that's causing you console.log grief. It may be related to either how the Babel transform or the Dev Tools are implemented... You can try a classic bind like this, to see if it helps:
onClick=this.somehandler
constructor()
this.somehandler = this.somehandler.bind(this);
somehandler()
// ....
render()
return <button onClick=this.somehandler>...</button>
constructor() this.alert = this.alert.bind(this); works, and the debugger console shows correct message. I also believe it is due to Babel, but can't not prove it
– Xiaoliang Sha
Aug 26 at 14:08
And i found it is recommended NOT use arrow function in render, because it will create a function wrapper. Ref stackoverflow.com/questions/34350988/…
– Xiaoliang Sha
Aug 26 at 15:00
yes, it's true that you should avoid anonymous (arrow) functions as handlers.
– Dan
Aug 26 at 15:42
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Do this onClick=() => this.alert instead of onClick=this.alert when you use arrow functions
– Think-Twice
Aug 26 at 9:30