React 生命周期
創(chuàng)建階段
constructor
模塊創(chuàng)建
構造函數(shù),組件被創(chuàng)建時調用一次,有且只調用一次,為默認state賦初始值。
componentWillMount
模塊創(chuàng)建階段渲染前
組件即將被渲染的時候調用,render()函數(shù)之前調用,有且只調用一次,在組件渲染之前進行的操作:操作默認state
componentWillMount(){
console.log("組建即將被渲染");
console.log(this.state);
//對默認state進行處理
}
componentDidMount
模塊創(chuàng)建階段最后一步
組件已經(jīng)被渲染之后調用,render()函數(shù)之后,有且只調用一次
componentDidMount(){
//render函數(shù)執(zhí)行之后調用
//發(fā)送請求,請求數(shù)據(jù)
}
render()
組件state發(fā)生變化,就會執(zhí)行。
render(){
}
更新階段
componentWillReceiveProps
組件將要接受props時調用,多次調用,只要有數(shù)據(jù)props更新,它就會被調用
componentWillReceiveProps(props){
console.log("組件即將接受數(shù)據(jù)");
console.log(props)
//更新當前組件的state
this.setState({
image:this.props.image
})
}
shouldComponentUpdate
在接受數(shù)據(jù)函數(shù)調用之后調用,用于阻止當前組件更新
shouldComponentUpdate(){
console.log("組建被更新之前阻止");
//state驗證
//true 不阻止
return false;
}
componentWillUpdate
如果不阻止更新,在render之前調用
componentWillUpdate(){
console.log("組件即將被更新");
}
componentDidUpdate
更新之后,render渲染結束調用
componentDidUpdate(){
console.log("組件被渲染完成之后調用");
}
銷毀階段
componentWillUnmount()
在組件被卸載和銷毀之前立刻調用??梢栽谠摲椒ɡ锾幚砣魏伪匾那謇砉ぷ?,例如解綁定時器,取消網(wǎng)絡請求,清理任何在componentDidMount環(huán)節(jié)創(chuàng)建的DOM元素。