在项目过程中遇到了同一文件路径不同参数,路由跳转后并未调用componentWillDidMount,因此用到了React新生命周期:static getDerivedStateFromProps(nextProps, preState)并在此记录!
getDerivedStateFromProps的出现: componentWillReceiveProps在React新的生命周期中被取消,这个生命周期函数是为了替代componentWillReceiveProps,所以在需要使用componentWillReceiveProps的时候,就可以考虑使用getDerivedStateFromProps来进行替代了。
getDerivedStateFromProps的功能: 我的理解:getDerivedStateFromProps这个方法名已经非常语义话了,简单翻译过来就是从Props中获得State,所以该函数的功能就是从更新后的props中获取State,它让组件在 props 发生改变时更新它自身的内部 state。
getDerivedStateFromProps的参数: nextProps:与componentWillReceiveProps的nextProps参数相同。
preState:原数据state中各数据的值。
getDerivedStateFromProps的触发条件: 会在调用 render 方法之前调用,即在渲染 DOM 元素之前会调用,并且在初始挂载及后续更新时都会被调用。
结合下图新React生命周期理解起来会简单一些:![]()
文章图片
getDerivedStateFromProps的使用:1.当props数据某个值发生变化时对state进行赋值:
static getDerivedStateFromProps(nextProps, preState) {
const {match: {params: {instrumentId}}} = nextProps;
// 此处当传入的instrumentId发生变化的时候,更新state
if (instrumentId !== preState.instrumentId) {
return {
instrumentId: instrumentId,
};
}
return null;
// 不变化,则对于state不进行任何操作
}
2.无条件的根据 prop 来更新内部 state,也就是只要有传入 prop 值, 就更新 state
(但是如果只要props值改变,就更新state,其实直接用props的值去进行操作就可以了。)
static getDerivedStateFromProps (props, state) {
const {match: {params: {instrumentId}}} = nextProps;
return {
instrumentId: instrumentId,
}
}
3.因为getDerivedStateFromProps被定义为静态方法,所以不可以直接使用this.×××,因此我们需要对类进行实例化,才使用类中定义的方法:
class InstrumentCommand extends PureComponent {
......
static getDerivedStateFromProps(nextProps, preState) {
const {match: {params: {instrumentId}}} = nextProps;
if (instrumentId !== preState.instrumentId) {
new InstrumentCommand(nextProps).implementDispatch(instrumentId)
}
}
}
......
getDerivedStateFromProps的注意事项: 【React新生命周期getDerivedStateFromProps的理解与使用】1.getDerivedStateFromProps方法一定要return一个值,如果不需要对state操作,只需return null;即可,不可返回undefined。
当getDerivedStateFromProps()没有明确返回任何内容时,控制台会输出警告: