跳到主要内容位置

React生命周期详解

  • 生命周期图谱 (常用生命周期函数已用粗体标出)

fhc24J.png

  • 何为生命周期函数?​

生命周期函数指组件在某一特定时刻会自动调用执行的函数​


  • Mounting阶段

mounting 阶段中包含三个小的生命周期函数:componentWillMount、render、componentDidMount。

// componentWillMount 代码
componentWillMount() {
console.log('componentWillMount-----组件即将挂载到页面的时刻');
}
// componentDidMount 代码
componentDidMount() {
console.log('componentDidMount-----组件挂载完成的时刻');
}
// render 代码
render(){
console.log('3-组件挂载中......');
}

Attention:componentWillMount 和 componentDidMount 只会在页面刷新的时候才会执行,而 render 每次组件中 props 或 state 更新都会调用
​

  • Updation阶段

    updation 阶段,即组件发生改变的更新阶段,主要包括两大部分,props 属性的改变和state状态的改变。主要有:getDerivedStateFromProps(React v16中为 componentWillReceiveProps)、shouldComponentUpdate、componentWillUpdate(React v17中已遗弃)、componentDidUpdate。
    ​

// getDerivedStateFromProps 代码
getDerivedStateFromProps() {
console.log('child--getDerivedStateFromProps-----发生调用')
}

Attention:getDerivedStateFromProps 函数只在非顶层组件中才会调用,即需要接收props属性才会发生调用

getDerivedStateFromProps 也就是说这个组件第一次存在于Dom中,此函数是不会被执行的;  如果已经存在于Dom中,函数才会被执行

// shouldComponentUpdate 代码
shouldComponentUpdate() {
console.log('1-shouldComponentUpdate-----组件发生改变前执行');
return true
}

Attention:shouldComponentUpdate 要求返回一个布尔类型的值,若返回true,则组件才会进行更新,若返回false,则组件不会更新

// componentWillUpdate 代码
//WARNING! To be deprecated in React v17. Use componentDidUpdate instead.
componentWillUpdate() {
console.log('2-componentWillUpdate-----组件更新前,shouldComponentUpdate 之后调用');
}

Attention:componentWillUpdate 的调用发生在 shouldComponentUpdate 之后,且仅在 shouldComponentUpdate 返回 true 的时候,componentWillUpdate 才会执行

// componentDidUpdate 代码
componentDidUpdate() {
console.log('4-componentDidUpdate-----组件更新之后调用,组件更新的最后一步');
}