看起来componentWillReceiveProps
将在即将发布的版本中完全淘汰,取而代之的是一种新的生命周期方法getDerivedStateFromProps
:静态 getDerivedStateFromProps()。
经过检查,您现在似乎无法在this.props
和之间进行直接比较nextProps
,就像在 中一样componentWillReceiveProps
。有没有办法解决?
此外,它现在返回一个对象。我假设返回值本质上是正确的this.setState
吗?
下面是我在网上找到的一个例子:State衍生自 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;
}
}