[React]React Component 中function的LifeCycle

  • 720
  • 0
  • 2016-03-05

當呼叫React.createClass()以建立React Component時,需要傳入一個自訂物件給該funciton。這個物件可以任意的定義其成員,但一定要有一個function-render()才行。除了render()之外,React的LifeCycle還有其他function參與在其中,可以因應不同的需求將邏輯寫在各function中。

[React]React Component 中function的LifeCycle

當呼叫React.createClass()以建立React Component時,需要傳入一個自訂物件給該funciton。這個物件可以任意的定義其成員,但一定要有一個function-render()才行。除了render()之外,React的LifeCycle還有其他function參與在其中,可以因應不同的需求將邏輯寫在各function中。

var ComponentTest = React.createClass({
    render() {  
        return(
            <div>
                Hello World
            </div>
        );
    }
});

render()

此function是必需存在的(required),且需要回傳單一的DOM element,該element可以是native的DOM componet(例如:<div/>),或是透過React定義的component。

也可以回傳null或是false以表示不想產生任何的物件。

render()最好保持簡單(pure),也就是說,最好不要在function內進行Componet狀態的改變。如果想要做一些事情,例如依據Browser以進行一些UI的更動。則盡量在componentDidMount()或是其他lifecycle function中進行。

如果this.propsthis.state有改變,React就會再次呼叫render()以處理這些資料變動所帶來的UI改變。

如果該Component有子Componet的話,此父Componet的render()執行順序會早於子Component的。

Initialize-初始化

getInitialState()

此function會在component被掛載(mount)到DOM前被呼叫,且只會被呼叫一次。此function需要回傳一個物件,該物件會被用為this.state的初始值。

getDefaultProps()

這個function是用來設定this.props的預設值的,如果父元件沒有指派prop,則會使用此預設值。

    getDefaultProps() { 
        return {
                propKey : 'default value' 
        }; 
    }, 

Mounting-掛載React Component到DOM

componentWillMount()

這個function是在該Component被掛載到DOM之前被呼叫,只會被呼叫一次,呼叫順序在getInitialState()之後,但在render()之前。所以如果在此function中呼叫setState(),雖然this.state已經改變了,但並不會讓render()額外再執行一次。

componentDidMount()

此function是在建立好Component(render())並掛載到DOM後被呼叫,也是只會被呼叫一次而已。在這個時間點之後,就可以透過this.refs正常的存取children。

因為React元件是可以包含子React Component,所以子ComponentcomponentDidMount()被呼叫的順序是早於父Component的。

如果想要使用其他的JavaScript framework,最好是在這個method中呼叫,並使用setTimeout或是setInterval的方式來叫用。

componentWillUnmount()

此function會在component被卸離(unmount) DOM時被呼叫,所以一些清除(cleanup)的工作可以在這裡執行。

所以幾個主要的function的執行順序如下圖所示: 圖-執行順序

Updating-更新props或state

componentWillReceiveProps()

當Component的props被更改時,此function會被呼叫。也就是說,初始的render在執行時,此function並不會被叫用。

如果有邏輯是要依據this.props透過this.setState()來修改this.state的話,則可以寫在此function中,以避免額外的render()被觸發。新的props可以透過傳入的argument-nextProps來存取,而舊的則是透過this.props來存取。

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

注意: 相對於this.propsthis.state並沒有所謂的componentWillReceiveState()來處理state的改變。如果想要處理state的改變,可以使用componentWillUpdate()

componentWillUpdate()

void componentWillUpdate(
  object nextProps, object nextState
)

此function會在更改後的props或state被接收時被呼叫,時間點會早於render()。同樣的,初始的render在執行時,此function並不會被叫用。

注意: 在這個function中無法使用this.setState(),如果要因應props的變更修改this.state,則要使用componentWillReceiveProps()

componentDidUpdate()

void componentDidUpdate(
  object prevProps, object prevState
)

此function會在component改變且更新到DOM後被呼叫,如果要在component更新完後再操作DOM的物件,則可以使用此function。


參考: