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