本文基于react 18
- 当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下
- constructor 构造
- getDerivedStateFromProps 从props中获取state
- render 渲染
- componentDidMount 结束挂载
- 当组件state中数据发生变化时,其生命周期调用顺序如下
- getDerivedStateFromProps 从props中获取state
- shouldComponentUpdat 组件是否渲染,返回true则往下执行,返回false则到此为止
- render 渲染
- getSnapshotBeforeUpdate 获取更新前快照
- componentDidUpdate 组件更新
constructor
constructor(props)
如果不需要初始化state或进行其他初始化操作,constructor可以省略
constructor(props) {
super(props)
this.state = {
//初始化state中的某些值
}
}
getDerivedStateFromProps
static getDerivedStateFromProps(nextProps, currentState)
从props中获取状态state,返回一个对象或null
/**
* nextProps 下一状态的props
* currentState 当前state
**/
static getDerivedStateFromProps(nextProps, currentState){
console.log('[从Props中获取state:getDerivedStateFromProps]',nextProps, currentState)
return {msg:nextProps.info}
}
render
render(): ReactNode;
渲染界面,页面布局的控件就写在这里面;但是return必须是只能有一个根结点。
render() {
console.log('[渲染:render]')
return(
<div></div>
)
}
componentDidMount
componentDidMount?(): void;
挂载完成后的操作
componentDidMount() {
console.log('[挂载后:componentDidMount]')
}
getSnapshotBeforeUpdate
getSnapshotBeforeUpdate?(prevProps: Readonly, prevState: Readonly): SS | null
获取更新前的props和state快照,返回值是state新值或null,返回null,state不做改变,返回对象则state更新
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('[更新前获取快照:getSnapshotBeforeUpdate]',prevProps,prevState)
return {res:'success'}
}
componentDidUpdate
componentDidUpdate?(prevProps: Readonly, prevState: Readonly, snapshot?: SS): void
组件更新后,可获取更新前的state和props
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('[组件更新:componentDidUpdate]',prevProps,prevState,snapshot)
}
标签:生命周期,render,getDerivedStateFromProps,React,state,prevState,props,prevProps
From: https://www.cnblogs.com/JarryShu/p/16937633.html