天天看點

React Native之元件(Component)生命周期學習筆記

1、Component介紹

一般Component需要被其它類進行繼承,Component和Android一樣,也有生命周期

英文圖檔如下

React Native之元件(Component)生命周期學習筆記
2   具體說明

1)、挂載階段

constructor() //構造函數,聲明之前先調用super(props)

componentWillMount()//因為它發生在render()方法前,是以在該方法内同步設定狀态不會引發重渲染

render()//元件加載,該方法必須要有,傳回一個React元素,

componentDidMount()//元件加載完成後觸發,執行個體化網絡請,設定定時器,設定監聽,設定狀态會導緻重渲染

2)、更新階段:該階段表示由狀态或屬性的改變導緻元件的重渲染

componentWillReceiveProps(nextProps)://該方法會在加載好的元件在收到新的狀态後調用,這裡可以使用setState函數。

shouldComponentUpdate(nextProps, nextState):該方法用來告訴React,元件輸出是否受到目前狀态或屬性的影響,預設情況下,每次狀态改變都會導緻重渲染,初次渲染不會調用該方法。

componentWillUpdate():該方法在收到新屬性和狀态渲染前調用,初次渲染不會調用該方法。

render():該方法是mount和update階段都會使用到的方法,

componentDidUpdate(prevProps, prevState):更新發生後會立即調用該方法,初次渲染不會調用該方法。

3)、銷毀階段

componentWillUnmount():該方法會在元件被銷毀前立即調用,實作一些清理工作,如清除定時器,取消網絡請求或者是清理其他在componentDidMount()方法内建立的DOM元素。

3  總結:

一般建議componentWillMount,componentDidMount,componentWillReceiveProps方法修改state值

在componentDidMount中,執行個體化網絡請,設定定時器,設定監聽。