componentWillMount 组件将要挂载,可以进行api的数据获取
componentDidMount 组件已经挂载,可以进行dom操作
下面就看一下页面运行后的输出语句,可以看到是先执行componentWillMount 组件,再去执行componentDidMount组件的
此时我们加上构造器和组件渲染的过程(数字是刷新后加上去的执行顺序,方便理解)
此时再次刷新页面,可以看到构造函数执行后会去执行componentWillMount组件,并对组件进行render中的渲染操作,然后组件就会完成挂载,输出如下
componentWillReceiveProps ⽗组件传递的属性有变化,做相应响应
shouldComponentUpdate 组件是否需要更新,返回布尔值,优化点
componentWillUpdate 组件将要更新
componentDidUpdate 组件已经更新
componentWillUnmount 组件已经销毁
下面直接写出所有的组件,全部输出,增加了两个定时器,第一个定时器显示组件传递的属性被更新,第二个定时器用来控制组件的更新
import React, { Component } from 'react'
class LifecycleChildren extends Component {
constructor(props){
super(props)
console.log('1.构造函数')
}
componentWillMount() {
//组件将要挂载,此时可以进行api调用和获取数据,但是不可以进行dom操作
console.log('2.组件将要挂载')
}
componentDidMount () {
//组件已经挂载,可以进行dom操作
console.log('4.组件已经挂载')
}
componentWillReceiveProps(){
//父组件传递的属性有变化,可以在这个函数做相应的相应操作
console.log('5.父组件传递的属性更新')
}
shouldComponentUpdate(){
//组件是否需要更新,需要返回一个布尔值,返回true更新,false不更新
console.log('6.组件是否应该更新,需要返回布尔值')
return true
}
componentWillUpdate(){
//组件将要更新
console.log('7.组件将要更新')
}
componentDidUpdate(){
//组件已经更新
console.log('8.组件已经更新')
}
componentWillUnmount(){
//组件销毁
console.log('组件已经销毁')
}
render() {
console.log('3.组件渲染')
return (
<div>
组件的生命周期
</div>
)
}
}
export default class Lifecycles extends Component {
constructor(props){
super(props)
this.state={
children:'我是生命周期',
showChildren:true
}
setTimeout(()=>{
this.setState({
children:'update'
})
},2000)
setTimeout(()=>{
this.setState({
showChildren:false
})
},4000)
}
render() {
return (
<div>
{this.state.showChildren?<LifecycleChildren title={this.state.children}></LifecycleChildren>:<div>组件已销毁</div>}
</div>
)
}
}
运行效果图如下,会先执行1234,2秒后执行属性更新,再2秒后由于组件显示更新为了false,所以组件销毁
本篇文章只是浅层的了解一下组件的生命周期,并没有做深入的探索,只适用于我这种小白入门的一个大概了解,仅供参考。