I have been struggling with trying to migrate my React code from ES5 to ES6. As I have found out by now, this
is no longer automatically bound which causes all sorts of hell.
I am trying to figure out by trial and error what objects are being passed around. So far I can find everything and adjust accordingly. However when it comes to this.setState I am having problems because it is not visible in console.log!!!! See screenshot in ES5:
and here is the same kind of code in ES6:
Please teach me how to fish i.e. help me figure out how to understand when an object has this.setState or not?
things i have tried
- from googling around i understand you might be able to default bind everything by changing the base component. unfortunately this did not work when it came to this.setState. It looks identical to the ES5 version of
this
in console so I concluded that setState is still not being bound somehow
To oversimplify how
this
works in JS:instance.foo()
) thenthis
refers to that object instance.foo()
), thenthis
is eitherundefined
or the global object, depending on whether strict mode is in effect.var bar = instance.foo; bar();
.Again, this is an oversimplification; MDN has details.
As this applies to React, and as explained in the React documentation on "Handling Events":
In your code, you render your
RawInput
asYou're passing a reference
updateValue
function in as a simple function, sothis
will not be bound withinupdateValue
.Basically, any time you pass a function as a React prop, unless you've bound it yourself, it's likely an error. The symptom is typically that
this
is undefined. In your code, it's a little more complicated:The RawInput's
updateValue
property is the unbound functionApp.updateValue
, but because you're invoking it asthis.props.updateValue
, it's being called as if it were a method ofthis.props
- sothis
refers to the RawInput'sprops
. That's why your console.log is showing an object with only two properties (start
andupdateValue
): it isn't thatsetState
isn't bound or went away, it's thatupdateValue
wasn't bound, sothis
isn't what you expect withinupdateValue
.To fix the issue, as the React docs explain:
updateValue={(value) => this.updateValue(value)}
updateValue(modifiedValue) {...}
withupdateValue = (modifiedValue) => {...}
.updateValue
yourself. For example: