Here's a bit of code, within a react component class (scaffolded using CRA 2)
click = () => {
console.log(this, "hello");
let x = 1 + 1; //This is just here to let chrome put a break point here.
}
When this code runs, it will print the component object to the console.
However - if I attach a debugger to that point, both Chrome (68), and Firefox (63) will show 'this' as undefined.
What's going on here?
Is it something to do with the transform-class-properties babel plugin being used to create click as a class property?
Edit: Yes, that seems like exactly what it is.
If we manually bind the method like:
constructor() {
super();
this.click2 = this.click2.bind(this);
}
click2() {
console.log(this, "hello");
let x = 1 + 1;
}
then it works fine.
In any case - is there a convenient way to solve this, so I don't have to put all those bind statements in?
from Chrome, Firefox debuggers not displaying the correct value for 'this' in a react app
No comments:
Post a Comment