this is undefined in getDerivedStateFromProps
See original GitHub issueDo you want to request a feature or report a bug? Bug
What is the current behavior?
this
is undefined in getDerivedStateFromProps
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn’t have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:
class MyComponent extends Component {
static sayHello() {
console.log('Hello')
}
static getDerivedStateFromProps() {
this.sayHello()
}
}
What is the expected behavior? I would expect the above to work. To me it is unexpected that a static method is not getting called on the class.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? 16.5.1
This seems like an easy fix to me, here
Is there a reason not to change line 157 and 161?
// From this
getDerivedStateFromProps.(nextProps, prevState);
// To this?
getDerivedStateFromProps.call(ctor, nextProps, prevState);
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (7 by maintainers)
this
in a static method can be the constructor (not the instance)Outside of what @TrySound has linked, this is how JS works. Static methods do not have access to a class instance’s
this
, and IMO, it never should.