react生命周期函数
import React, { Component } from 'react'
class LifeCycleSon 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 LifeCycle extends Component{
constructor(props){
super(props)
this.state={
son:"我是声明周期",
show:true
}
setTimeout(()=>{
this.setState({
son:"更新"
})
},2000)
setTimeout(()=>{
this.setState({
show:false
})
},4000)
}
render(){
const {son,show} = this.state;
return(
<div>
{show?<LifeCycleSon title={son}></LifeCycleSon>:<div>组件已销毁</div>}
</div>
)
}
}
运行结果
constructor》componentWillMount》render》componentDidMount
更新
componentWillReceiveProps》shouldComponentUpdate》componentWillUpdate》render》componentDidUpdate
setState(state)的改变会触发4个生命周期钩子----本组件
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
props的改变会触发5个生命周期钩子----子组件
componentWillReveiceProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate