方法名 |
作用 |
|
---|---|---|
constructor |
構造函數,初始化需要的state |
1次 |
componentWillMount |
控件渲染前觸發 |
1次 |
rander |
渲染控件的方法 |
多次 |
componentDidMount |
控件渲染後觸發 |
1次 |
componentWillReceiveProps |
組件接收到新的props時被調用 |
多次 |
shouldComponentUpdate |
當組件接收到新的props和state時被調用 |
多次 |
componentWillUpdate |
props或者state改變,並且此前的shouldComponentUpdate方法返回爲 true會調用該方法 |
多次 |
componentDidUpdate |
組件重新渲染完成後會調用此方法 |
多次 |
componentWillUnmount |
組件卸載和銷燬之前被調用 |
1次 |
1,執行順序
初次加載:依次觸發了父控件的構造函數,componentwillMount,render,子控件的構造函數,子控件的componentwillMount,render,componentwillMount,最後纔是父控件的componentwillMount。初次的渲染週期是從外向內逐步渲染,內部完成後纔算整體結束。
UI更新:一圈一摸一樣的流程完成刷新.
卸載:也是從外向內觸發,最後纔是父控件的componentwillUnmount。
2,幾點建議:
constructor()方法裏初始化state
componentWillMount()可在方法裏對state進行最後的修改,在初始化render
之前執行,如果在這個方法內調用setState
,render()
知道state發生變化,並且只執行一次;
componentDidMount()方法裏跑網/耗時操作 ,在初始化render之後只執行一次,在這個方法內,可以訪問任何組件,componentDidMount()
方法中的子組件componentDidMount()方法在父組件之前執行;
componentWillReceiveProps當props
發生變化時執行,初始化render
時不執行,在這個回調函數裏面,你可以根據屬性的變化,通過調用this.setState()
來更新你的組件狀態,舊的屬性還是可以通過this.props
來獲取,這裏調用更新狀態是安全的,並不會觸發額外的render
調用
componentWillUnmount當組件要被從界面上移除的時候,就會調用componentWillUnmount()
,在這個函數中,可以做一些組件相關的清理工作,例如取消計時器、網絡請求等;
注意,不要在 constructor 或者 render 裏 setState(),這是因爲 constructor 已含 this.state={} ,而 render 裏 setState 會造成setState -> render -> setState -> render,能做的setState,只要是render前,就放在componentWillMount,render後,就放在 componentDidMount。這兩個 function 是 react lifecycle 中,最常使用的兩個。當然啦,還有其它的部分,那就以後研究和推敲它們的使用時機咯!