React Native 中 component 生命週期

React Native中的component跟Android中的activity,fragment等一樣,存在生命週期,下面先給出component的生命週期圖

這裏寫圖片描述

getDefaultProps

object getDefaultProps()

執行過一次後,被創建的類會有緩存,映射的值會存在this.props,前提是這個prop不是父組件指定的 
這個方法在對象被創建之前執行,因此不能在方法內調用this.props ,另外,注意任何getDefaultProps()返回的對象在實例中共享,不是複製

getInitialState

object getInitialState()

控件加載之前執行,返回值會被用於state的初始化值

componentWillMount

void componentWillMount()

執行一次,在初始化render之前執行,如果在這個方法內調用setStaterender()知道state發生變化,並且只執行一次

render

ReactElement render()

render的時候會調用render()會被調用 
調用render()方法時,首先檢查this.propsthis.state返回一個子元素,子元素可以是DOM組件或者其他自定義複合控件的虛擬實現 
如果不想渲染可以返回null或者false,這種場景下,React渲染一個<noscript>標籤,當返回null或者false時,ReactDOM.findDOMNode(this)返回null 
render()方法是很純淨的,這就意味着不要在這個方法裏初始化組件的state,每次執行時返回相同的值,不會讀寫DOM或者與服務器交互,如果必須如服務器交互,在componentDidMount()方法中實現或者其他生命週期的方法中實現,保持render()方法純淨使得服務器更準確,組件更簡單

componentDidMount

void componentDidMount()

在初始化render之後只執行一次,在這個方法內,可以訪問任何組件,componentDidMount()方法中的子組件在父組件之前執行

從這個函數開始,就可以和 JS 其他框架交互了,例如設置計時 setTimeout 或者 setInterval,或者發起網絡請求

shouldComponentUpdate

boolean shouldComponentUpdate(
  object nextProps, object nextState
)
  • 1
  • 2
  • 3

這個方法在初始化render時不會執行,當props或者state發生變化時執行,並且是在render之前,當新的props或者state不需要更新組件時,返回false

shouldComponentUpdate: function(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}
  • 1
  • 2
  • 3

shouldComponentUpdate方法返回false時,講不會執行render()方法,componentWillUpdatecomponentDidUpdate方法也不會被調用

默認情況下,shouldComponentUpdate方法返回true防止state快速變化時的問題,但是如果·state不變,props只讀,可以直接覆蓋shouldComponentUpdate用於比較propsstate的變化,決定UI是否更新,當組件比較多時,使用這個方法能有效提高應用性能

componentWillUpdate

void componentWillUpdate(
  object nextProps, object nextState
)
  • 1
  • 2
  • 3

propsstate發生變化時執行,並且在render方法之前執行,當然初始化render時不執行該方法,需要特別注意的是,在這個函數裏面,你就不能使用this.setState來修改狀態。這個函數調用之後,就會把nextPropsnextState分別設置到this.propsthis.state中。緊接着這個函數,就會調用render()來更新界面了

componentDidUpdate

void componentDidUpdate(
  object prevProps, object prevState
)
  • 1
  • 2
  • 3

組件更新結束之後執行,在初始化render時不執行

componentWillReceiveProps

void componentWillReceiveProps(
  object nextProps
)
  • 1
  • 2
  • 3

props發生變化時執行,初始化render時不執行,在這個回調函數裏面,你可以根據屬性的變化,通過調用this.setState()來更新你的組件狀態,舊的屬性還是可以通過this.props來獲取,這裏調用更新狀態是安全的,並不會觸發額外的render調用

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}
  • 1
  • 2
  • 3
  • 4
  • 5

componentWillUnmount

void componentWillUnmount()

當組件要被從界面上移除的時候,就會調用componentWillUnmount(),在這個函數中,可以做一些組件相關的清理工作,例如取消計時器、網絡請求等

總結

React Native的生命週期就介紹完了,其中最上面的虛線框和右下角的虛線框的方法一定會執行,左下角的方法根據props state是否變化去執行,其中建議只有在componentWillMount,componentDidMount,componentWillReceiveProps方法中可以修改state

英文地址:https://facebook.github.io/react/docs/component-specs.html#lifecycle-methods

轉自:https://blog.csdn.net/ElinaVampire/article/details/51813677

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章