生命週期函數指在某一個時刻組件會自動調用執行的函數,React的生命週期函數主要有
- Initialization(初始化)
- Mounting(掛載)
- Updation(更新)
- Unmounting(卸載)
![clipboard.png clipboard.png](http://static.javashuo.com/static/loading.gif)
父組件
// 在組件即將被掛載到頁面的時刻自動執行,掛載完畢再也不執行
componentWillMount() {
console.log('componentWillMount')
}
render() {
console.log('parent render');
return //JSX
}
// 組件被掛載到頁面以後,自動被執行,掛載完畢再也不執行
componentDidMount() {
console.log('componentDidMount')
}
// 組件被更新以前,自動被執行
shouldComponentUpdate() {
console.log('shouldComponentUpdate')
return true;
}
// 組件被更新以前,它會自動執行,可是它在shouldComponentUpdate以後執行
// 若是shouldComponentUpdate返回true它才執行
// 返回false,這個函數就不會被執行了
componentWillUpdate() {
console.log('componentWillUpdate')
}
// 組件更新完成以後自動被執行
componentDidUpdate() {
console.log('componentDidUpdate')
}
子組件
// 一個組件從父組件接收了參數
// 若是這個組件第一次存在於父組件中,不會執行
// 若是這個組件以前已經存在於父組件中,纔會執行
componentWillReceiveProps() {
console.log('child componentWillReceiveProps')
}
// 當這個組件即將被從頁面中剔除的時候,會被執行
componentWillUnmount() {
console.log('child componentWillUnmount')
}