看起来它将componentWillReceiveProps
在即将发布的版本中完全淘汰,取而代之的是新的生命周期方法getDerivedStateFromProps
:static getDerivedStateFromProps()。
经过检查,看来您现在无法在this.props
和之间进行直接比较nextProps
,就像您可以在componentWillReceiveProps
。有没有办法解决?
而且,它现在返回一个对象。我是否正确假设返回值本质上是this.setState
?
以下是我在网上找到的示例:状态源自props / state。
之前
class ExampleComponent extends React.Component {
state = {
derivedData: computeDerivedState(this.props)
};
componentWillReceiveProps(nextProps) {
if (this.props.someValue !== nextProps.someValue) {
this.setState({
derivedData: computeDerivedState(nextProps)
});
}
}
}
后
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;
}
}
componentWillReceiveProps