切换主题
父子组件生命周期
Vue 3
Vue 3 的生命周期钩子包括:
beforeCreate
: 实例初始化后,数据观测和事件配置之前。created
: 实例创建完成,数据观测和事件配置完成,但 DOM 未挂载。beforeMount
: 挂载开始之前,模板编译完成,但未插入 DOM。mounted
: 实例挂载到 DOM 后调用。beforeUpdate
: 数据更新时,DOM 重新渲染之前。updated
: 数据更新后,DOM 重新渲染完成。beforeUnmount
: 实例销毁之前。unmounted
: 实例销毁后。
父子组件生命周期顺序
- 父组件
beforeCreate
- 父组件
created
- 父组件
beforeMount
- 子组件
beforeCreate
- 子组件
created
- 子组件
beforeMount
- 子组件
mounted
- 父组件
mounted
更新时:
- 父组件
beforeUpdate
- 子组件
beforeUpdate
- 子组件
updated
- 父组件
updated
销毁时:
- 父组件
beforeUnmount
- 子组件
beforeUnmount
- 子组件
unmounted
- 父组件
unmounted
React 18
React 18 的生命周期方法包括:
constructor
: 组件初始化时调用。static getDerivedStateFromProps
: 在渲染前调用,返回新的 state。render
: 渲染组件。componentDidMount
: 组件挂载后调用。shouldComponentUpdate
: 决定组件是否更新。getSnapshotBeforeUpdate
: 在 DOM 更新前调用。componentDidUpdate
: 组件更新后调用。componentWillUnmount
: 组件卸载前调用。
特别注意,这里区别于Vue
,React
的函数组件生命周期在useEffect
钩子中具体表现如下:
- 当不传第二个参数时,在
useEffect
中能模拟DidMount
、DidUpdate
、WillUnmount
生命周期函数钩子。
jsx
const Component = () => {
useEffect(() => {
// DidMount
// DidUpdate ---> re-render时重新执行effect函数
return () => {
// WillUnmount
}
})
}
- 传入第二个参数并且是数据的
依赖state
数组,同上一种情况。
jsx
const Component = () => {
useEffect(() => {
// DidMount
// DidUpdate ---> re-render时重新执行effect函数
return () => {
// WillUnmount
}
}, [state])
}
- 传入第二个参数并且是空数组
[]
,模拟DidMount
、WillUnmount
生命周期函数钩子。
jsx
const Component = () => {
useEffect(() => {
// DidMount
return () => {
// WillUnmount
}
}, [])
}
父子组件生命周期顺序
- 父组件
constructor
- 父组件
static getDerivedStateFromProps
- 父组件
render
- 子组件
constructor
- 子组件
static getDerivedStateFromProps
- 子组件
render
- 子组件
componentDidMount
- 父组件
componentDidMount
更新时:
- 父组件
static getDerivedStateFromProps
- 父组件
shouldComponentUpdate
- 父组件
render
- 子组件
static getDerivedStateFromProps
- 子组件
shouldComponentUpdate
- 子组件
render
- 子组件
getSnapshotBeforeUpdate
- 父组件
getSnapshotBeforeUpdate
- 子组件
componentDidUpdate
- 父组件
componentDidUpdate
销毁时:
- 父组件
componentWillUnmount
- 子组件
componentWillUnmount
总结
- Vue 3: 父组件先初始化,子组件挂载完成后父组件挂载。更新和销毁时,父组件先触发钩子,子组件随后。
- React 18: 父组件先初始化并渲染,子组件随后初始化和渲染。更新和销毁时,父组件先触发钩子,子组件随后。
两者在生命周期顺序上有所不同,但都遵循从父到子的顺序。