【发布时间】:2018-09-12 00:53:06
【问题描述】:
看起来componentWillReceiveProps 将在即将发布的版本中完全淘汰,取而代之的是新的生命周期方法getDerivedStateFromProps:static getDerivedStateFromProps()。
经检查,您现在无法像在 componentWillReceiveProps 中那样直接比较 this.props 和 nextProps。有没有办法解决这个问题?
此外,它现在返回一个对象。我是否正确假设返回值本质上是this.setState?
下面是我在网上找到的一个例子:State derived from 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;
}
}
【问题讨论】:
-
标题应该是“尽管 React 团队竭尽全力反对它,但如何让事情顺利进行”
标签: javascript reactjs lifecycle