-
Notifications
You must be signed in to change notification settings - Fork 47.2k
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
Improve warning message for failure to initialize state
when using getDerivedStateFromProps
#12670
Comments
I'm also wondering why this is necessary? I'm experiencing a case where this would break down in the type system because my code expects an array to have certain values based on props, and actually throws an error in example: const State = {foo: Array<'key1' | 'key2'>}
const Props = {key1: string, key2: string}
component<Props, State> {
state = {
foo: [], // later throws an error when I am expecting this to be populated
}
static getDrivedStateFromProps(nextProps) {
const foo = Object.keys(bar);
if (foo.length === 0) throw new Error(); // gurantee foo is populated
return {
foo
}
}
} |
related: #12523 |
I am opening a PR for that if nobody minds 😄 |
Not at all, please go ahead! |
gaearon
pushed a commit
that referenced
this issue
Aug 3, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you want to request a feature or report a bug?
bug
What is the current behavior?
The warning for a failure to initialize state when using
getDerivedStateFromProps
is not as clear as it could be.This component produces the warning:
The warning can be resolved by adding
state = {}
either in the class definition or the constructor, or by not usinggetDerivedStateFromProps
.See reactjs/react.dev#796 for more detail on why this warning message can be counter-intuitive.
Since the warning is specific to the use of
getDerivedStateFromProps
and not triggered by any other state or lifecycle methods, and state initialization isn't required for other state methods likethis.setState
, it would make sense to me to mentiongetDerivedStateFromProps
explicitly in the warning.Here's a proposal for a new warning message:
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React >= 16.3.0
The text was updated successfully, but these errors were encountered: