生命周期簡介
像 Android 開發一樣,React Native(RN) 中的組件也有生命周期(Lifecycle)。
這張圖很簡潔直觀地告訴我們,生命周期的整個流程以及階段劃分。
第一階段
getDefaultProps -> getInitialState -> componentWillMount ->render ->componentDidMount。 事實上,每個組件都會經歷這個流程生命周期,是一個組件創建跟加載的過程。
getDefaultProps和getInitialState是對state跟props的初始化和設置,當然現在比較流行的寫法,是直接在contructor構造器中直接對這兩個狀態進行設置
compinentWillMount:該方法可以進行一些業務的初始化,或者訂閱RN廣播。特別注意的是,在整個生命周期中,該方法只會被調用一次。
render,渲染方法,絕對不能在該方法調用改變狀態的的方法(setState)!
componentDidMount:主要作用是通知組件已經加載完成。需要注意的是,RN 框架是先調用子組件的 componentDidMount() ,然后調用父組件的函數。該方法在整個生命周期中也是只調用一次!
第二階段
運行中 ->屬性(props)改變( 父層界面發生改變) ->componentWillReceiveProps->shouldComponentUpdate—true—>componentWillUpdate->render->componentDidUpdate ->運行中。當然還有運行中—(狀態發生改變)—>shouldComponentUpdate-…, 該過程發生在用戶界面交互過程中。
componentWillReceiveProps:如果組件收到新的屬性(props),就會調用該方法。在這個回調函數里面,你可以根據屬性的變化,通過調用 this.setState() 來更新你的組件狀態,這里調用更新狀態是安全的,并不會觸發額外的 render() 調用。
shouldComponentUpdate:默認情況下,這個函數永遠返回 true 用來保證數據變化的時候 UI 能夠同步更新
componentWillUpdate:其函數原型:void componentWillUpdate(object nextProps, object nextState),在這個方法中,可以做一些在更新界面之前要做的東西。不過在這里面,你就不能使用 this.setState 來修改狀態。這個函數調用之后,就會把 nextProps 和 nextState 分別設置到 this.props 和 this.state 中。這個函數執行完,緊接著就會調用 render() 來更新界面了。
componentDidUpdate:調用了 render() 更新完成界面之后,會調用 componentDidUpdate() 來得到通知
第三階段
卸載前->componentWillUnmount ->結束
componentWillUnmount:當組件要被從界面上移除的時候,就會調用該方法,可以在該方法中做一些清理的工作,比如清除RN廣播,清除數據等
總結
生命周期 調用次數 能否使用setSate()
getDefaultProps 1(全局調用一次) 否
getInitialState 1 否
componentWillMount 1 是
render >=1 否
componentDidMount 1 是
componentWillReceiveProps >=0 是
shouldComponentUpdate >=0 否
componentWillUpdate >=0 否
componentDidUpdate >=0 否
componentWillUnmount 1 否
如果覺得此文不錯,麻煩幫我點下“喜歡”。么么噠!