一個react組件在瀏覽器中存在三種狀態:1(組件掛載)Mounting 2(組件更新)Updating 3(組件卸載)Unmounting
每個狀態下有它自己的聲明周期函數:
(組件掛載)Mounting
組件掛載就是組件實例從被創建到插入DOM中的過程,是組件初次渲染的過程,會依次執行下面函數:
-
constructor(props, context)
--構造函數,在組件被創建時候調用 一次 -
componentWillMount()
--在組件被渲染之前(render()
方法被調用之前)調用。所以在此函數中進行setstate
不會導致組件重復渲染。componentWillMount()
是唯一一個在服務器端渲染調用的生命周期鉤子,不過一般建議用constructor()
-
render()
--react組件中必不可少的核心函數,切記不可以在此函數中使用setState
修改state
,因為每次setState
改變state
都會重新渲染組件;否則會造成死循環。 -
componentDidMount()
--在組件掛載之后立即執行,適用于一些如:需要初始化DOM節點的操作或者AJAX請求等。在該鉤子函數中進行setState()
操作會導致組件重新渲染。組件內部可以通過ReactDOM.findDOMNode(this)
來獲取當前組件的節點,然后就可以像Web開發中那樣操作里面的DOM元素了
(組件更新)Updating
當props
、state
中的任意一項發生改變,或者調用this.forceUpdate
時,都會導致組件更新和重新渲染。組件更新時,調用以下函數:
-
componentWillReceiveProps(nextProps)
--一個已掛載的組件接收到新的props
之前調用。
如果需要更新狀態以響應prop更改(例如,重置它),則可以比較this.props
和nextProps
,并在此方法中使用this.setState
執行狀態轉換。mounting
狀態不會調用此方法,調用this.setState
不會觸發此方法。 -
shouldComponentUpdate(nextProps, nextState)
--當組件接收到新的props
或者state
時,要進行rendering之前會調用。該鉤子函數用于告訴React組件是否需要重新渲染, 其默認返回true
。目前,如果shouldComponentUpdate()
返回false,則不會調用componentWillUpdate()
,render()
和componentDidUpdate()
。 請注意,將來React可能會將shouldComponentUpdate()
作為提示而不是嚴格指令,并且返回false仍可能導致組件的重新呈現。 -
componentWillUpdate(nextProps, nextState)
--shouldComponentUpdate()
返回true
或者調用forceUpdate()
之后或者props有改變,該鉤子函數會被調用。不能在這里調用setState
,如果需要設置state
,應該在componentWillReceiveProps()
中調用setState()
。初始化組件時不執行此方法。 -
render()
-- -
componentDidUpdate()
--組件更新之后調用此方法,在此方法中可以操作DOM。
(組件卸載)Unmounting
組件從DOM中移除時,調用一下方法:
-
componentWillUnmount()
--在組件卸載和銷毀前調用,ReactDOM.unmountComponentAtNode()
可以觸發此方法。在此方法中做一些清理事情,一般在componentDidMount()
中注冊的事件都需要取消,比如:取消定時器,取消網絡請求,解綁DOM事件。
注意:
- react的所有生命周期函數中當且僅有
render()
函數是必須的,其他生生命周期函數都是非必需的。 -
setState()
通常在componentWillMount()
componentDidMount()
componentWillReceiveProps()
以及componentDidUpdate()
這幾個生命周期鉤子函數中調用;componentWillUpdate()
和render()
這兩個生命周期函數中嚴禁調用setState()
。