getDerivedStateFromProps method
ReactJS lifecycle method that is invoked before rendering when new props (nextProps
) are received.
It should return a new Map
that will be merged into the existing component state,
or null
to do nothing.
Important Caveats:
-
Unlike componentWillReceiveProps, this method is called before first mount, and re-renders.
-
prevState
will benull
when this lifecycle method is called before first mount. If you need to make use ofprevState
, be sure to make your logic null-aware to avoid runtime exceptions. -
This method is effectively
static
(since it is static in the JS layer), so using instance members like props, state orref
will not work.This is different than the componentWillReceiveProps method that it effectively replaces.
If your logic requires access to instance members - consider using getSnapshotBeforeUpdate instead.
Example:
@override
getDerivedStateFromProps(Map nextProps, Map prevState) {
if (prevState['someMirroredValue'] != nextProps['someValue']) {
return {
someMirroredValue: nextProps.someValue
};
}
return null;
}
Deriving state from props should be used with caution since it can lead to more verbose implementations that are less approachable by others.
See: reactjs.org/docs/react-component.html#static-getderivedstatefromprops
Implementation
@override
getDerivedStateFromProps(Map nextProps, Map prevState) {
final tNextProps = typedPropsFactory(nextProps);
final tPrevState = typedStateFactory(prevState);
if (tNextProps.isShown! && _isOrWillBeHidden(tPrevState.$transitionPhase)) {
return _stateToBeginShowing(tNextProps, tPrevState.$transitionPhase);
} else if (!tNextProps.isShown! && _isOrWillBeShown(tPrevState.$transitionPhase)) {
return _stateToBeginHiding(tNextProps, tPrevState.$transitionPhase);
}
return null;
}