1、lifecycle methods(下稱lm)是指在元件的生命周期中的特定時間點被呼叫的methods
你可以寫一個lm在一個元件第1次render之前呼叫
你可以寫一個lm在一個元件每次render之後呼叫,除了第1次render
你可以在元件的生命周期中的諸多不同時機點執行lm
2、lm有3種類別:
mounting、updating、unmounting
mounting monent:
元件在它首次render時掛載(mounts),這也是mounting類別的lm執行的時機點
mounting lm有3種:
componentWillMount//在render之前執行(html元素載入之前)
render(載入html元素)
componentDidMount//在render之後執行(html元素載入之後)
當元件掛載時依序執行這3個lm
除了render(同時屬於updating類別),另外兩個只在首次render時執行
componentDidMount(下稱cdm)在render之後執行,如果你用ajax來取得初始資料,則cdm很適合用來執行這個工作,它也適合用來連結外部應用,例如web api或是js framework,也很適合用它來設定timers,使用setTimeout或setInterval
updating moment:
元件在首次render時沒有update,元件在每次render時update,除了第1次,每個元件每次update都會自動執行它的updating lm
updating lm有5種依執行先後順序排列如下:
componetWillRecieveProps(下稱cwrp)
shouldComponentUpdate(scu)
componentWillUpdate(cwu)
render
componentDidUpdate(cdu)
cwrp只有在元件有接收props的情況下會被呼叫,時機點如下例(引用codecademy範例)所示
// componentWillReceiveProps will get called here:
ReactDOM.render(
<Example prop="myVal" />,
document.getElementById('app')
);
// componentWillReceiveProps will NOT get called here:
ReactDOM.render(
<Example />,
document.getElementById('app')
);
cwrp自動接收一個nextProps參數,這個參數是一個物件,內容和即將傳入的props相同,一般用來事前比對,符合條件才render該prop或是做其他處理
scu在cwrp之後執行,自動接收兩個參數,nextProps, nextState,並回傳true或false,若回傳true則正常update,但若回傳的是false,則不會執行後續的3個updating lm,包含render 。通常用來比對nextProps和this.props以及nextState,thisState,依據結果回傳true or false,判斷是否update
範例: https://codepen.io/anon/pen/wqPxYX?editors=1011
cwu在scu之後執行,同樣自動接收兩個參數nextProps以及nextState,你不能在cwu中呼叫setState
cwu通常用來和react結構之外的物件互動,如果你需要在元件render之前做一些非react的設定,例如檢查window size或是和外部api互動,那麼cwu是一個適合的地方
render觸發ui重渲染,需注意的是即使未從parent component接收任何props,當parent re-render時其所有children component都會觸發render,而有時因為html架構需求,即使不需要從parent接收props,仍會有成為其child的需要,因此有時會需要使用scu判斷是否需要re-render以避免parent更新時child進行不必要的re-render
cdu在rendered html完成載入後執行,並自動接收prevProps, prevState兩個參數,它們參照到update之前的元件props和state,可以用來和"現況"的props還有state比較
cdu通常和cwu一樣是用來和react環境之外的物件互動,例如browser和api,差別只在它是render之後
unmounting moment:
一個元件的unmounting期間發生在元件從dom中移除時,這可以發生在dom rerender,但未包含該元件時,或是使用者導向到其他網頁,或是關閉瀏覽器時
unmounting moment只有一個lm:
componentWillUnmount(cwun)
cwun在元件從dom移除之前被呼叫,因此如果即將被移除的元件曾經設定需要被清理的方法(例如用setInterval設定的timer),那麼該元件的cwun就是適合你清理這些方法的時機和地方
沒有留言:
張貼留言