【React自制全家桶】五、React元件的生命週期函式詳解
阿新 • • 發佈:2019-01-04
一、總覽React元件的生命週期函式
什麼是生命週期函式:簡單的來說就是 在某個時刻會自動執行的函式
二、React的生命週期函式主要由四塊組成
分別是:元件初始化、元件掛載、元件更新、元件解除安裝
三、生命週期之元件初始化
作用:元件初始時設定props和state
四、生命週期之元件掛載
作用:元件掛載時執行的操作
//在元件即將被掛載到頁面上時自動執行(掛載之前) componentWillMount(){ console.log('componentWillMount'); } //渲染頁面 render() //在元件即將被掛載到頁面後時自動執行(掛載之後) componentDidMount(){ console.log('componentDidMount'); }
五、生命週期之元件更新
作用:元件更新時執行的操作
//頂層元件不執行 //當元件從父元件中接受引數,父元件的render函式重新執行,則子元件該函式執行 componentWillReceiveProps(){ console.log('componentWillReceiveProps'); } //在元件被更新之前自動執行 shouldComponentUpdate(){ console.log('shouldComponentUpdate'); //當return為turn,則更新被執行。當返回為false,則更新被取消 return true; } //元件被更新之前執行。當shouldComponentUpdate返回false時不執行 componentWillUpdate(){ console.log('componentWillUpdate'); } //渲染頁面 render() //在元件更新完成之後執行 componentDidUpdate(){ console.log('componentDidUpdate'); }
六、生命週期之元件解除安裝
作用:元件解除安裝時執行的操作
//當元件即將解除安裝時執行
componentWillUnmount(){
console.log('child componentWillUnmount');
}
七、注意事項
不管是父元件還是子元件都有自己的生命週期函式