It looks like componentWillReceiveProps
is going to be completely phased out in coming releases, in favor of a new lifecycle method getDerivedStateFromProps
:static getDerivedStateFromProps().
Upon inspection, it looks like you are now unable to make a direct comparison between this.props
and nextProps
, like you can in componentWillReceiveProps
. Is there any way around this?
Also, it now returns an object. Am I correct to assume that the return value is essentially this.setState
?
Below is an example I found online: State derived from props/state.
Before
class ExampleComponent extends React.Component {
state = {
derivedData: computeDerivedState(this.props)
};
componentWillReceiveProps(nextProps) {
if (this.props.someValue !== nextProps.someValue) {
this.setState({
derivedData: computeDerivedState(nextProps)
});
}
}
}
After
class ExampleComponent extends React.Component {
// Initialize state in constructor,
// Or with a property initializer.
state = {};
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.someMirroredValue !== nextProps.someValue) {
return {
derivedData: computeDerivedState(nextProps),
someMirroredValue: nextProps.someValue
};
}
// Return null to indicate no change to state.
return null;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…