下圖詳細列述了 React 組件在整個生命周期中所涉及的方法和行為:
生命周期詳解
組件在整個 ReactJS 的生命周期中,主要會經歷這4個階段:創建階段、實例化階段、更新階段、銷毀階段。下面對各個階段分別進行介紹。
1. 創建階段
- 該階段主要發生在創建組件類的時候,即調用
React.createClass
時觸發 - 這個階段只會觸發一個 getDefaultProps方法,該方法返回一個對象并緩存起來。然后與父組件指定的
props
對象合并,最后賦值給this.props
作為該組件的默認屬性 -
getDefaultProps
方法,只在組件創建時調用一次
2. 實例化階段
(1)getInitialState:初始化組件的state
的值。其返回值會賦值給組件的 this.state
屬性
(2)componentWillMount:根據業務邏輯來對state
進行相應的操作。只會在裝載之前調用一次,在 render 之前調用
(3)componentDidMount:
- 對根據虛擬
DOM
結構而生的真實DOM
進行相應的處理。組件內部可以通過ReactDOM.findDOMNode(this)
來獲取當前組件的節點,然后就可以像 Web 開發中那樣操作里面的DOM
元素- 只會在裝載完成之后調用一次,在 render 之后調用
3. 更新階段
(1)componentWillReceiveProps:當組件接收到新的 props
時,會觸發該函數。在改函數中,通常可以調用 this.setState
方法來完成對 state
的修改
(2)shouldComponentUpdate:該方法用來攔截新的 props
或 state,然后根據事先設定好的判斷邏輯,做出最后要不要更新組件的決定
(3)componentWillUpdate:當上面的方法攔截返回 true 的時候,就可以在該方法中做一些更新之前的操作
(4)componentDidUpdate:該方法在組件的更新已經同步到 DOM
中去后觸發,我們常在該方法中做一 DOM
操作
4. 銷毀階段
- 這個階段只會觸發一個叫 componentWillUnmount 的方法。
- 當組件需要從
DOM
中移除的時候,我們通常會做一些取消事件綁定、移除虛擬DOM
中對應的組件數據結構、銷毀一些無效的定時器等工作。這些事情都可以在這個方法中處理。
調用順序及次數
getDefaultProps()
,調用1次
getInitialState()
,調用1次
componentWillMount()
,調用1次
render()
,調用>=1次
componentDidMount()
:僅客戶端,調用1次
componentWillReceiveProps(object nextProps)
,調用>=0次
ShouldComponentUpdate(object nextProps, object nextState)
,調用>=0次
componentWillUpdate(object nextProps, object nextState)
,調用>=0次
render()
,調用>=1次
componentDidUpdate(object prevProps, object prevState)
,調用>=0次
componentWillUnmount()
,調用1次
示例代碼點擊這里
參考資料:
http://www.hangge.com/blog/cache/detail_1473.html#
http://lib.csdn.net/article/reactnative/43548
https://hulufei.gitbooks.io/react-tutorial/component-lifecycle.html
http://pinggod.com/2015/React-%E7%BB%84%E4%BB%B6%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/
https://segmentfault.com/a/1190000005161417