SOVMedCare Tech

@sovmedcare


  • 首頁

  • 關於

  • 作者群

  • 標籤

  • 分類

  • 歸檔

React LifeCycle

Tu-Szu-Chi 發表於 2017-09-04

React LifeCycle
圖為React主要的生命週期LifeCycle流程,以下內容將針對各週期的觸發時機以及使用場合做解說


componentWillMount

  • 時機
    所有DOM加載之前

  • 場合
    可在root-component做連結外部API的設定,ex.Firebase config

不建議在此做this.setState,因setState是屬異步(Async)操作,不能保證能立即執行完畢
設Default state時,官方也建議寫在constructor()裡
整體來說componentWillMount是較少被用到的LifeCycle,可選擇將Code寫在constructor()中

1
2
3
4
constructor(props){
super(props)
// Do something...
}

componentDidMount

  • 時機
    所有DOM加載之後

  • 場合
    Call API

建議有需要做AJAX API皆可寫在componentDidMount裡
因Call API後通常會牽涉到state來操作,在此實作AJAX可確保所有Component皆已加載

componentWillReceiveProps

  • 時機
    接收到新的props前

  • 場合
    比較this.props & nextProps

1
2
3
4
5
componentWillReceiveProps(nextProps){
(nextProps.id !== this.props.id) &&
this.setState({LoadingData:true})
// Get data by nextProps.id ...
}

以上範例表示說當新的props.id !== this.props.id時,我們就要去獲取新的Data
且componentWillReceiveProps在初始化(initial props -> mounting)時,並不會呼叫此LifeCycle

shouldComponentUpdate

  • 時機
    有新的props || state

  • 場合
    回傳true或false決定Component是否要re-render

(nextProps , nextState) => Boolean

雖然避免部分做多餘的re-render看似能提升效能,但據說React團隊認為不該輕易使用它
尤其當你使用了後,卻察覺不出提升的效益,那就不要去用它
更多的資訊可參考這篇什麼時候要使用shouldComponentUpdate

componentWillUpdate

  • 時機
    有新的props || state 且 shouldComponentUpdate return true

  • 場合
    和componentWillReceiveProps相似
    此LifeCycle較少用到,且在此不能使用到this.setState,這會造成不斷的輪迴週期

componentDidUpdate

  • 時機
    Component update後

  • 場合
    Call API when component updated

此處和componentDidMount也有點相似,官方也建議有需要在Component更新後做的Network request寫在這
也可以做些需要reset的動作

componentWillUnmount

  • 時機
    Component將卸載

  • 場合
    Cancel network request / Remove event listeners

最常觸發的時機應為跳頁時,如有setTimeout或setInterval的network request記得在此取消掉
或是任何在componentDidMount建立的DOM也在此移除


Reference

官方文檔
React Lifecycle Methods
什麼時候要使用shouldComponentUpdate

1…34
SOVMedCare

SOVMedCare

Full Stack JS #FRP #RxJS #Redux #React

31 文章
19 標籤
GitHub E-Mail FB Page Instagram
© 2017 — 2020 SOVMedCare
由 Hexo 強力驅動
|
主題 — NexT.Gemini v5.1.2
0%