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





Do this onClick=() => this.alert instead of onClick=this.alert when you use arrow functions
– Think-Twice
Aug 26 at 9:30






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)