看起来它将componentWillReceiveProps在即将发布的版本中完全淘汰,取而代之的是新的生命周期方法getDerivedStateFromProps:static getDerivedStateFromProps()。
componentWillReceiveProps
getDerivedStateFromProps
经检查,它看起来像你现在无法作出直接比较this.props和nextProps,就像你可以在componentWillReceiveProps。有没有办法解决?
this.props
nextProps
而且,它现在返回一个对象。我是否正确假设返回值本质上是this.setState?
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:你应该能够与组合来处理它的用途getDerivedStateFromProps和componentDidUpdate,看到的阵营博客文章,例如迁移。是的,返回的对象getDerivedStateFromProps的状态更新与传递给的对象类似setState。
componentDidUpdate
setState
万一您确实需要道具的旧值,可以随时使用以下内容将其缓存在状态中:
state = { cachedSomeProp: null // ... rest of initial state }; static getDerivedStateFromProps(nextProps, prevState) { // do things with nextProps.someProp and prevState.cachedSomeProp return { cachedSomeProp: nextProps.someProp, // ... other derived state properties }; }
任何不影响状态的东西都可以放入componentDidUpdate,甚至还有一个getSnapshotBeforeUpdate用于底层的东西。
getSnapshotBeforeUpdate
更新:要了解新的(和旧的)生命周期方法,react-lifecycle- visualizer软件包可能会有所帮助。