react組件生命週期

1. Component生命週期

生命週期 調用次數 可否使用 setSate()
getDefaultProps 1(全局調用一次)
getInitialState 1
componentWillMount 1
render >=1
componentDidMount 1
componentWillReceiveProps >=0
shouldComponentUpdate >=0
componentWillUpdate >=0
componentDidUpdate >=0
componentWillUnmount 1

1.1 getDefaultProps

組件建立以前,會先調用 getDefaultProps(),這是全局調用一次,嚴格地來講,這不是組件的生命週期的一部分。安全

1.2 getInitialState

在組件被建立並加載後,首先調用 getInitialState(),來初始化組件的狀態。網絡

1.3 componentWillMount

而後,準備加載組件,會調用 componentWillMount(),這個函數調用時機是在組件建立,並初始化了狀態以後,在第一次繪製 render() 以前。能夠在這裏作一些業務初始化操做,也能夠設置組件狀態。這個函數在整個生命週期中只被調用一次。框架

1.4 render渲染顯示

1.5 componentDidMount

在組件第一次繪製以後,會調用 componentDidMount(),通知組件已經加載完成。這個函數調用的時候,其虛擬 DOM 已經構建完成,你能夠在這個函數開始獲取其中的元素或者子組件了。須要注意的是,RN 框架是先調用子組件的 componentDidMount(),而後調用父組件的函數。從這個函數開始,就能夠和 JS 其餘框架交互了,例如設置計時 setTimeout 或者 setInterval,或者發起網絡請求。這個函數也是隻被調用一次。這個函數以後,就進入了穩定運行狀態,等待事件觸發。函數

1.6 componentWillReceiveProps(nextProps)

若是組件收到新的屬性(props),就會調用 componentWillReceiveProps(),輸入參數 nextProps 是即將被設置的屬性,舊的屬性仍是能夠經過 this.props 來獲取。在這個回調函數裏面,你能夠根據屬性的變化,經過調用 this.setState() 來更新你的組件狀態,這裏調用更新狀態是安全的,並不會觸發額外的 render() 調用。性能

1.7 shouldComponentUpdate(nextProps, nextState)

當組件接收到新的屬性和狀態改變的話,都會觸發調用 shouldComponentUpdate(...),輸入參數 nextProps 和上面的 componentWillReceiveProps 函數同樣,nextState 表示組件即將更新的狀態值。這個函數的返回值決定是否須要更新組件,若是 true 表示須要更新,繼續走後面的更新流程。否者,則不更新,直接進入等待狀態。
默認狀況下,這個函數永遠返回 true 用來保證數據變化的時候 UI 可以同步更新。在大型項目中,你能夠本身重載這個函數,經過檢查變化先後屬性和狀態,來決定 UI 是否須要更新,能有效提升應用性能。this

1.8 componentWillUpdate(nextProps, nexxtState)

若是組件狀態或者屬性改變,而且上面的 shouldComponentUpdate(...) 返回爲 true,就會開始準更新組件,並調用 componentWillUpdate(),輸入參數與 shouldComponentUpdate 同樣,在這個回調中,能夠作一些在更新界面以前要作的事情。須要特別注意的是,在這個函數裏面,你就不能使用 this.setState 來修改狀態。這個函數調用以後,就會把 nextProps 和 nextState 分別設置到 this.props 和 this.state 中。緊接着這個函數,就會調用 render() 來更新界面了。code

1.9 componentDidUpdate(prevProps, prevState)

調用了 render() 更新完成界面以後,會調用 componentDidUpdate() 來獲得通知,由於到這裏已經完成了屬性和狀態的更新了,此函數的輸入參數變成了 prevProps 和 prevState。component

1.10 componentWillUnmount

當組件要被從界面上移除的時候,就會調用 componentWillUnmount(),在這個函數中,能夠作一些組件相關的清理工做,例如取消計時器、網絡請求等。 參考地址:React Native 中組件的生命週期生命週期

2. id的定義

id: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
相關文章
相關標籤/搜索