前言
React的生命周期从广义上分为三个阶段:挂在,渲染,卸载
挂载时期
-
constructor
- constructor中完成了React数据的初始化,它接受两个参数:props和context,当想在函数内部使用这两个参数,需要用super()传入这两个参数
- 只要使用了constructor()如果要使用this必须要写上super(),否则this指向错误
-
componentWillMount(即将废弃)
-
render
- 渲染阶段
-
componentDidMount
- 组件初始化渲染完成阶段调用
更新过程
-
componentWillReceiveProps
- 接受一个参数nextProps
- 组件的props属性可以通过父组件来更改,这时,componentWillReceiveProps将被调用。可以在这个方法里更新state,触发render方法重新渲染组件
-
shouldComponentUpdate
- 主要用于性能优化
-
componentWillUpdate(即将废气)
-
render
-
componentDidUpdate(prevProps,prevState)
- 组件更新完成后被调用,可以访问并修改dom
销毁时
-
componentWillUnmount
- 组件销毁前调用 移除 定时器,监听等
新增的生命周期
-
getDerivedStateFromProps
- 字面意思从props中获取state
- 代替componentWillReceiveProps
- getDerivedStateFromProps是一个静态函数,接收两个参数nextProps, prevState,禁止使用this访问this.props
-
getSnapshotBeforeUpdate
- 在render之前调用,state已经更新
- 无条件的更具props来更新内部state
- 只有props值和state值不同时才更新state值
- 类似function组件中的effect hooks