React Native中的component跟Android中的activity,fragment等同樣,存在生命週期,下面先給出component的生命週期圖react
object getDefaultProps()
android
執行過一次後,被建立的類會有緩存,映射的值會存在this.props
,前提是這個prop不是父組件指定的
這個方法在對象被建立以前執行,所以不能在方法內調用this.props
,另外,注意任何getDefaultProps()
返回的對象在實例中共享,不是複製緩存
object getInitialState()
安全
控件加載以前執行,返回值會被用於state的初始化值服務器
void componentWillMount()
網絡
執行一次,在初始化render
以前執行,若是在這個方法內調用setState
,render()
知道state發生變化,而且只執行一次框架
ReactElement render()
函數
render的時候會調用render()
會被調用
調用render()
方法時,首先檢查this.props
和this.state
返回一個子元素,子元素能夠是DOM組件或者其餘自定義複合控件的虛擬實現
若是不想渲染能夠返回null或者false,這種場景下,React渲染一個<noscript>
標籤,當返回null或者false時,ReactDOM.findDOMNode(this)
返回null
render()
方法是很純淨的,這就意味着不要在這個方法裏初始化組件的state,每次執行時返回相同的值,不會讀寫DOM或者與服務器交互,若是必須如服務器交互,在componentDidMount()
方法中實現或者其餘生命週期的方法中實現,保持render()
方法純淨使得服務器更準確,組件更簡單性能
void componentDidMount()
this
在初始化render以後只執行一次,在這個方法內,能夠訪問任何組件,componentDidMount()
方法中的子組件在父組件以前執行
從這個函數開始,就能夠和 JS 其餘框架交互了,例如設置計時 setTimeout 或者 setInterval,或者發起網絡請求
boolean shouldComponentUpdate( object nextProps, object nextState )
這個方法在初始化render
時不會執行,當props或者state發生變化時執行,而且是在render
以前,當新的props
或者state
不須要更新組件時,返回false
shouldComponentUpdate: function(nextProps, nextState) { return nextProps.id !== this.props.id; }
當shouldComponentUpdate
方法返回false時,講不會執行render()
方法,componentWillUpdate
和componentDidUpdate
方法也不會被調用
默認狀況下,shouldComponentUpdate
方法返回true防止state
快速變化時的問題,可是若是·state
不變,props
只讀,能夠直接覆蓋shouldComponentUpdate
用於比較props
和state
的變化,決定UI是否更新,當組件比較多時,使用這個方法能有效提升應用性能
void componentWillUpdate( object nextProps, object nextState )
當props
和state
發生變化時執行,而且在render
方法以前執行,固然初始化render時不執行該方法,須要特別注意的是,在這個函數裏面,你就不能使用this.setState
來修改狀態。這個函數調用以後,就會把nextProps
和nextState
分別設置到this.props
和this.state
中。緊接着這個函數,就會調用render()
來更新界面了
void componentDidUpdate( object prevProps, object prevState )
組件更新結束以後執行,在初始化render
時不執行
void componentWillReceiveProps( object nextProps )
當props
發生變化時執行,初始化render
時不執行,在這個回調函數裏面,你能夠根據屬性的變化,經過調用this.setState()
來更新你的組件狀態,舊的屬性仍是能夠經過this.props
來獲取,這裏調用更新狀態是安全的,並不會觸發額外的render
調用
componentWillReceiveProps: function(nextProps) { this.setState({ likesIncreasing: nextProps.likeCount > this.props.likeCount }); }
componentWillUnmount
void componentWillUnmount()
當組件要被從界面上移除的時候,就會調用componentWillUnmount()
,在這個函數中,能夠作一些組件相關的清理工做,例如取消計時器、網絡請求等
React Native的生命週期就介紹完了,其中最上面的虛線框和右下角的虛線框的方法必定會執行,左下角的方法根據props
state
是否變化去執行,其中建議只有在componentWillMount
,componentDidMount
,componentWillReceiveProps
方法中能夠修改state
值