-
Notifications
You must be signed in to change notification settings - Fork 47k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
this is undefined in getDerivedStateFromProps #14730
Comments
@sanbornhilland This is expected. #12612 (comment) |
Outside of what @TrySound has linked, this is how JS works. Static methods do not have access to a class instance's |
It's not even I understand wanting to avoid unnecessary confusion in the |
this is intended, and yes it does differ from how static methods, work if you call them with the class to the left of the dot |
@milesj I'm not sure what you mean by
That's demonstrably false so maybe I'm misunderstanding your point. |
@sanbornhilland That's how JS works. |
You can see their usage here:
They are simply calling it as a reference. No bind/call/apply, etc. This is standard JS classes. |
@milesj Sorry mate, don't want to turn this into a debate but you're misreading your console output. Your example code demonstrates that Appreciate the link to the code but that just proves the point I was making. When you assign the function like that then you lose the context of EDIT: Just to be clear. I think I understand the confusion now. Perhaps you thought I was asking for Anyway, I see that this is a deliberate decision by the React team so that's fine. I appreciate the quick response, all. |
|
@sanbornhilland Correct, I was assuming you wanted the instance, not the constructor. Definitely clears up the confusion. |
This works (not recommended though): static get getDerivedStateFromProps() {
return (props, state) => {
console.log("Hello this is ", this);
};
} |
This issue should be reopened because static get getDerivedStateFromProps() {
return this._getDerivedStateFromProps.bind(this);
} |
Do you want to request a feature or report a bug?
Bug
What is the current behavior?
this
is undefined ingetDerivedStateFromProps
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:
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?
The text was updated successfully, but these errors were encountered: