組件生命周期
React組件的生命周期可分成三個(gè)狀態(tài):
- Mounting:組件掛載
- Updating:組件更新
- Unmounting:組件卸載

-
componentWillMount()
在組件即將被掛載到頁面的時(shí)刻自動執(zhí)行 -
render()
數(shù)據(jù)變化自動執(zhí)行 -
componentDidMount()
組件被掛載到頁面之后,自動執(zhí)行 -
componentWillReceiveProps()
當(dāng)一個(gè)組件從父組件接受一個(gè)參數(shù)只要父組件的render函數(shù)重新被執(zhí)行,子組件的這個(gè)生命周期函數(shù)就會被執(zhí)行。換一種說法,如果這個(gè)組件第一次存在與父組件中,不會執(zhí)行如果這個(gè)組件之前已經(jīng)存在父組件中,才會執(zhí)行。 -
shouldComponentUpdate()
組件被更新之前會會自動執(zhí)行 -
componentWillUpdate()
組件被更新之前,它會自動執(zhí)行,但是它在shouldComponentUpdate ()之后被執(zhí)行。如果shouldComponentUpdate ()return true,這個(gè)函數(shù)才會被執(zhí)行;如果shouldComponentUpdate ()return false,這個(gè)函數(shù)就不會被執(zhí)行了. -
componentDidUpdate()
組件更新完成之后會自動執(zhí)行 -
componentWillUnmount()
當(dāng)這個(gè)組件即將被從頁面中剔除的時(shí)候
生命周期函數(shù)的使用場景
1.在子組件里面使用shouldComponentUpdate(),避免無謂render函數(shù)的渲染
????首先我們看一下下面這種情況,當(dāng)不在生命周期函數(shù)里面做任何處理的話。在父組件todoList的input中輸入文字時(shí),子組件todoItem也會跟著渲染。
????但是理想的情況下,todoItem應(yīng)該只有在點(diǎn)擊提交按鈕或者刪除的時(shí)候子組件todoItem才會渲染。

????當(dāng)傳入的內(nèi)容發(fā)生改變時(shí)return true,才進(jìn)行渲染,當(dāng)內(nèi)容不發(fā)生改變的情況下return false,不對todoItem進(jìn)行渲染。
shouldComponentUpdate (nextProps, nextState) {
// console.log('child shouldComponentUpdate')
if (nextProps.content !== this.props.content) {
return true
} else {
return false
}
}
效果就變成了了下面這樣的情況。提升了性能,避免無謂render函數(shù)的渲染

2.建議將ajax放在componentDidMount() 中執(zhí)行。
????如果在將ajax放在render()中會出現(xiàn)死循環(huán)。只要頁面的props或者state改變,render()就會被反復(fù)執(zhí)行,ajax就會反復(fù)請求。
???? 寫網(wǎng)頁的時(shí)候,把a(bǔ)jax放在componentWillMount()是沒有任何問題的,但是如果開發(fā)react Native,或者用react Native做服務(wù)器的同構(gòu),如果在componentWillMount()發(fā)送ajax請求,可能會和更高端的技術(shù)產(chǎn)生沖突。為了避免這種情況,干脆將ajax放在componentDidMount() 中。
(完)