react生命周期流程
1.初始化,首次render
-
getDefaultProps()
getDefaultProps 方法可以用來設(shè)置組件屬性的默認(rèn)值,在組件被建立時候就立即調(diào)用,所有實(shí)例都可以共享這些屬性。此時并不可以使用this.state和setState。
注意es6語法中就不這樣用了,在前面一篇文章中介紹過了區(qū)別。 -
getInitialState()
getInitialState 方法用于定義初始狀態(tài),也不可以使用this.state和setState。
-
componentWillMount()
componentWillMount只在初始化時候被調(diào)用一次,可以使用setState方法,會立即更新state,然后接著進(jìn)行render。
-
render()
注意在render中千萬不可使用setState方法,不然馬上會引起無限的報錯了哈哈。如果其中包含其他的子組件,那么子組件的生命周期才開始進(jìn)行。
-
componentDidmount()
在子組件也都加載完畢后執(zhí)行,在RN中就是指組件初始化加載完畢,在react中DOM渲染完成,此時就可以操作DOM了。
2.props發(fā)生改變時候更新
-
componentWillReceiveProps(nextProps)
componentWillReceiveProps方法可以比較this.props和nextProps來看是否發(fā)生了變化,然后可以進(jìn)行setState等操作。
注意只要父組件此方法觸發(fā),那么子組件也會觸發(fā),也就是說父組件更新,子組件也會跟著更新。
-
shouldComponentUpdate(nextProps, nextState)
shouldComponentUpdate 方法在接收了新的props或state后觸發(fā),你可以通過返回true或false來控制后面的生命周期流程是否觸發(fā)。
-
componentWillUpdate(nextProps, nextState)
componentWillUpdate在props或state改變或shouldComponentUpdate返回true后觸發(fā)。不可在其中使用setState。
-
render()
重新渲染。
-
componentDidupdate(prevProps, prevState)
會等子組件也都更新完后才觸發(fā)。
3.state發(fā)生改變時候更新
-
shouldComponentUpdate(nextProps, nextState)
shouldComponentUpdate 方法在setState后state發(fā)生改變后觸發(fā),你可以通過返回true或false來控制后面的生命周期流程是否觸發(fā)。
-
componentWillUpdate(nextProps, nextState)
componentWillUpdate在state改變或shouldComponentUpdate返回true后觸發(fā)。不可在其中使用setState。
-
render()
重新渲染。
-
componentDidupdate(prevProps, prevState)
會等子組件也都更新完后才觸發(fā)。
3.組件銷毀
-
componentWillUnmount()
組件銷毀時候觸發(fā)。
使用redux時候情況
在使用redux做狀態(tài)管理時候,基本不需要透過生命周期去做setState這樣的狀態(tài)管理了,基本都是用props來傳遞來重新渲染,需要注意的僅僅是在哪個生命周期時候觸發(fā)action,比如需要進(jìn)行ajax請求時候一般都是在componentDidMount和componentWillReceiveProps時候進(jìn)行,在reducer中處理完,然后在通過props傳入組件執(zhí)行組件的更新周期。
參考資料
2.掘金
3.ajax請求