Xiaoliang Sha
Xiaoliang Sha

Reputation: 23

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

Upvotes: 1

Views: 386

Answers (1)

Dan Inactive
Dan Inactive

Reputation: 10060

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.

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:

constructor() {
  this.somehandler = this.somehandler.bind(this);
} 

somehandler() {
   // ....
}

render() {
  return <button onClick={this.somehandler}>...</button>
}

Upvotes: 1

Related Questions