React生命周期详解
2021年9月 · 预计阅读时间: 1 分钟
- 生命周期图谱 (常用生命周期函数已用粗体标出)
- 何为生命周期函数?
生命周期函数指组件在某一特定时刻会自动调用执行的函数
- Mounting阶段
mounting 阶段中包含三个小的生命周期函数:componentWillMount、render、componentDidMount。
Attention:componentWillMount 和 componentDidMount 只会在页面刷新的时候才会执行,而 render 每次组件中 props 或 state 更新都会调用
Updation阶段
updation 阶段,即组件发生改变的更新阶段,主要包括两大部分,props 属性的改变和state状态的改变。主要有:getDerivedStateFromProps(React v16中为 componentWillReceiveProps)、shouldComponentUpdate、componentWillUpdate(React v17中已遗弃)、componentDidUpdate。
Attention:getDerivedStateFromProps 函数只在非顶层组件中才会调用,即需要接收props属性才会发生调用
getDerivedStateFromProps 也就是说这个组件第一次存在于Dom中,此函数是不会被执行的; 如果已经存在于Dom中,函数才会被执行
Attention:shouldComponentUpdate 要求返回一个布尔类型的值,若返回true,则组件才会进行更新,若返回false,则组件不会更新
Attention:componentWillUpdate 的调用发生在 shouldComponentUpdate 之后,且仅在 shouldComponentUpdate 返回 true 的时候,componentWillUpdate 才会执行
