組件生命周期
React組件的生命周期可分成三個狀態(tài):
- Mounting:組件掛載
- Updating:組件更新
- Unmounting:組件卸載
生命周期.png
-
componentWillMount()
在組件即將被掛載到頁面的時刻自動執(zhí)行 -
render()
數(shù)據(jù)變化自動執(zhí)行 -
componentDidMount()
組件被掛載到頁面之后,自動執(zhí)行 -
componentWillReceiveProps()
當一個組件從父組件接受一個參數(shù)只要父組件的render
函數(shù)重新被執(zhí)行事甜,子組件的這個生命周期函數(shù)就會被執(zhí)行吻贿。換一種說法郊艘,如果這個組件第一次存在與父組件中僚祷,不會執(zhí)行如果這個組件之前已經存在父組件中尺锚,才會執(zhí)行酷师。 -
shouldComponentUpdate()
組件被更新之前會會自動執(zhí)行 -
componentWillUpdate()
組件被更新之前讶凉,它會自動執(zhí)行,但是它在shouldComponentUpdate ()
之后被執(zhí)行山孔。如果shouldComponentUpdate ()
return true懂讯,這個函數(shù)才會被執(zhí)行;如果shouldComponentUpdate ()
return false,這個函數(shù)就不會被執(zhí)行了. -
componentDidUpdate()
組件更新完成之后會自動執(zhí)行 -
componentWillUnmount()
當這個組件即將被從頁面中剔除的時候
生命周期函數(shù)的使用場景
1.在子組件里面使用shouldComponentUpdate()
台颠,避免無謂render函數(shù)的渲染
????首先我們看一下下面這種情況褐望,當不在生命周期函數(shù)里面做任何處理的話。在父組件todoList的input中輸入文字時蓉媳,子組件todoItem也會跟著渲染譬挚。
????但是理想的情況下,todoItem應該只有在點擊提交按鈕或者刪除的時候子組件todoItem才會渲染酪呻。
組件-未處理.gif
????當傳入的內容發(fā)生改變時return true减宣,才進行渲染,當內容不發(fā)生改變的情況下return false玩荠,不對todoItem進行渲染漆腌。
shouldComponentUpdate (nextProps, nextState) {
// console.log('child shouldComponentUpdate')
if (nextProps.content !== this.props.content) {
return true
} else {
return false
}
}
效果就變成了了下面這樣的情況贼邓。提升了性能,避免無謂render函數(shù)的渲染
組件-已處理.gif
2.建議將ajax放在componentDidMount()
中執(zhí)行闷尿。
????如果在將ajax放在render()
中會出現(xiàn)死循環(huán)塑径。只要頁面的props或者state改變,render()
就會被反復執(zhí)行填具,ajax就會反復請求统舀。
???? 寫網頁的時候,把ajax放在componentWillMount()
是沒有任何問題的劳景,但是如果開發(fā)react Native誉简,或者用react Native做服務器的同構,如果在componentWillMount()
發(fā)送ajax請求盟广,可能會和更高端的技術產生沖突闷串。為了避免這種情況,干脆將ajax放在componentDidMount()
中筋量。
(完)