如何使用生命周期方法getDerivedStateFromProps而不是componentWillReceiveProps
看起来它将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
:你应该能够与组合来处理它的用途getDerivedStateFromProps
和componentDidUpdate
,看到的阵营博客文章,例如迁移。是的,返回的对象getDerivedStateFromProps
的状态更新与传递给的对象类似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
用于底层的东西。更新:要了解新的(和旧的)生命周期方法,react-lifecycle-
visualizer软件包可能会有所帮助。
-
何时使用componentWillReceiveProps生命周期方法?
2021-01-31 关注 0 浏览86 1答案
-
生命周期:componentDillMount之前调用componentWillReceiveProps
2021-01-31 关注 0 浏览75 1答案
-
可以将getDerivedStateFromProps用作componentWillReceiveProps的替代方法
2021-01-31 关注 0 浏览81 1答案
-
如何在React中将生命周期方法与钩子一起使用?
2021-01-31 关注 0 浏览98 1答案
-
从构造函数调用生命周期与生命周期方法
2021-01-31 关注 0 浏览191 1答案
-
下列哪个不是Activiy的生命周期()
2022-03-03 关注 0 浏览18 1答案
-
如何使用makeStyles设置组件样式并在Material UI中仍然具有生命周期方法?
2021-01-31 关注 0 浏览66 1答案
-
项目生命周期不同于产品生命周期,因为项目生命周期:
2022-05-21 关注 0 浏览28 1答案
-
如何在CDI环境中管理EntityManager生命周期(使用Tomcat)
2021-02-01 关注 0 浏览74 1答案
-
如何将Spring Bean的生命周期与webapps的生命周期联系起来?
2021-02-01 关注 0 浏览173 1答案