react生命週期函數 出場順序-應用場景

生命週期函數圖

在這裏插入圖片描述

生命週期函數應用場景

頁面首次掛載

componentWillMount

在組件即將被掛載到頁面的時刻自動執行,還沒被掛載到頁面,僅首次被掛載時被執行,輸入之後不會執行
順序:componentWillMount – render

componentDidMount

組件被掛載到頁面之後自動執行,僅首次被掛載時被執行,輸入之後不會執行
順序:componentWillMount – render – componentDidMount

請求Ajax數據,不放在render函數是爲了避免多次請求 — 最合理方式,就放在這裏
在組件被掛載到頁面上的時候會被請求,不會重複執行

componentDidMount () {
	{/* 生命週期函數, 初始化頁面向後臺請求數據 */}
	axios.get('/api/todolist')
		.then(() => 	{alert('succ')})
		.catch(() => 	{alert('error')})
}

render

組件被更新的時候,實時自動執行

組件被更新頁面

componentWillReceiveProps

子組件特有執行,只有props有
一個組件要從父組件接收參數,只要父組件的render函數被執行了,子組件的這個生命週期函數就會被執行
如果這個組件第一次存在於父組件中,不會執行
如果這個組件之前已經存在於父組件中,纔會執行

shouldComponentUpdate

組件被更新之前,會被執行
順序:shouldComponentUpdate(false) – render

放在子組件,返回false,不必時刻渲染,增強子組件的性能, nextProps, nextState接下來可能會變成什麼樣, 只有值變更過才渲染,避免過多的render的操作,減少創建虛擬dom的比對

shouldComponentUpdate (nextProps, nextState) {
	if (nextProps.content !== this.props.content) {
		return true;
	} else {
		return false;
	}
}

componentWillUpdate

組件被更新之前,會被執行
順序:shouldComponentUpdate(true) – componentWillUpdate – render

componentDidUpdate

組件被更新完成之後,會被執行
順序:shouldComponentUpdate(true) – componentWillUpdate – render – componentDidUpdate

組件被剔除

componentWillUnmount

把組件從頁面剔除的時候

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章