React Native之組件(Component)生命周期學(xué)習(xí)筆記
1、Component介紹
一般Component需要被其它類進(jìn)行繼承,Component和Android一樣,也有生命周期
英文圖片如下
2 具體說(shuō)明
1)、掛載階段
constructor() //構(gòu)造函數(shù),聲明之前先調(diào)用super(props)
componentWillMount()//因?yàn)樗l(fā)生在render()方法前,因此在該方法內(nèi)同步設(shè)置狀態(tài)不會(huì)引發(fā)重渲染
render()//組件加載,該方法必須要有,返回一個(gè)React元素,
componentDidMount()//組件加載完成后觸發(fā),實(shí)例化網(wǎng)絡(luò)請(qǐng),設(shè)置定時(shí)器,設(shè)置監(jiān)聽(tīng),設(shè)置狀態(tài)會(huì)導(dǎo)致重渲染
2)、更新階段:該階段表示由狀態(tài)或?qū)傩缘母淖儗?dǎo)致組件的重渲染
componentWillReceiveProps(nextProps)://該方法會(huì)在加載好的組件在收到新的狀態(tài)后調(diào)用,這里可以使用setState函數(shù)。
shouldComponentUpdate(nextProps, nextState):該方法用來(lái)告訴React,組件輸出是否受到當(dāng)前狀態(tài)或?qū)傩缘挠绊?,默認(rèn)情況下,每次狀態(tài)改變都會(huì)導(dǎo)致重渲染,初次渲染不會(huì)調(diào)用該方法。
componentWillUpdate():該方法在收到新屬性和狀態(tài)渲染前調(diào)用,初次渲染不會(huì)調(diào)用該方法。
render():該方法是mount和update階段都會(huì)使用到的方法,
componentDidUpdate(prevProps, prevState):更新發(fā)生后會(huì)立即調(diào)用該方法,初次渲染不會(huì)調(diào)用該方法。
3)、銷毀階段
componentWillUnmount():該方法會(huì)在組件被銷毀前立即調(diào)用,實(shí)現(xiàn)一些清理工作,如清除定時(shí)器,取消網(wǎng)絡(luò)請(qǐng)求或者是清理其他在componentDidMount()方法內(nèi)創(chuàng)建的DOM元素。
3 總結(jié):
一般建議componentWillMount,componentDidMount,componentWillReceiveProps方法修改state值
在componentDidMount中,實(shí)例化網(wǎng)絡(luò)請(qǐng),設(shè)置定時(shí)器,設(shè)置監(jiān)聽(tīng)。
作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號(hào):編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)