一、不建议使用的
UNSAFE_componentWillReceiveProps(nextProps)
UNSAFE_componentWillMount()
UNSAFE_componentWillUpdate(nextProps, nextState)
二、新增加的
getDerivedStateFromProps(nextProps, prevState)
1.父组件通知子组件pros发生变更时
2.子组件每次render前
3.首次构造时执行
getSnapshotBeforeUpdate(nextProps, prevState)
1.首次构造时不执行
2.子组件每次render后
三、UNSAFE_componentWillReceiveProps更新方案
1.由于getDerivedStateFromProps为static,所以无法调用this.props。
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// type可能由props驱动,也可能由state驱动,这样判断会导致state驱动的type被回滚,
// 如果子组件中设置type为不同的值,type到此依赖又被赋值为props中的值
if (type !== prevState.type) {
return {
type,
};
}
// 否则,对于state不进行任何操作
return null;
}
在state中增加prevPropEmail,prevState.prevPropEmail相当于this.props.email
state = {
email: this.props.email,
prevPropEmail: '',
};
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.email !== prevState.prevPropEmail) {
return {
email: nextProps.email,
prevPropEmail: nextProps.email,
};
}
return null;
}
返回值即,this.setSate中的对象,return null 或 return {} ,相当于this.setState({})进行整体的刷新
另一种不同写法
constructor(props) {
super(props);
this.state = {
type: 0,
props,
}
}
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
const {props} = prevState;
// 这段代码可能看起来非常混乱,这个props可以被当做缓存,仅用作判断
if (type !== props.type) {
return {
type,
props: {
type,
},
};
}
return null;
}
2.异步情况也可以由componentDidUpdate完成,如三方组件
// 原代码
UNSAFE_componentWillReceiveProps(nextProps) {
// Either centerOn has never been called, or it is a repeat and we should ignore it
if (
(nextProps.centerOn && !this.props.centerOn) ||
(nextProps.centerOn &&
this.props.centerOn &&
this.didCenterOnChange(this.props.centerOn, nextProps.centerOn))
) {
// 执行混合动画
this.centerOn(nextProps.centerOn);
}
}
public componentDidUpdate(prevProps: ImageZoomProps): void {
// Either centerOn has never been called, or it is a repeat and we should ignore it
if (
(this.props.centerOn && !prevProps.centerOn) ||
(this.props.centerOn && prevProps.centerOn && this.didCenterOnChange(prevProps.centerOn, this.props.centerOn))
) {
this.centerOn(this.props.centerOn);
}
}