iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 13
0
Modern Web

RRRR的世界 (Ruby on Rails + React + Redux)系列 第 13

Day 13, React Lifecycle 不搞懂就掰了

今天,開始。
一張圖道盡千言萬語。
Component Lifecycle
好,今天結束。
(什麼,太偷懶了)

好啦,一個一個講。

就算一個一個講還是要把getDefaultProps跟getInitialState跳過!
因為他們會含在我常用的constructor裡。
至於哪時候會用到他們,就是明天說了。

所以說第一個會先run constructor喔!

componentWillMount

React component即將要被Mount上網頁時,會執行的片段。有一種說法是這段function很少被使用,幾乎可以搬移到constructor裡。

只呼叫一次!

render

DOM物件產生,就是把你寫在這個Component裡的 JSX 生成到頁面上。

componentDidMount

確定Mount上以後會呼叫一次,通常會在這邊執行一些AJAX呼叫、this.getDOMNode()找到自己的DOM,也可以在這邊呼叫setTimeout之類的function。

只呼叫一次

到這邊,你就可以初步看到你的DOM了。
接下來就是每次每次的更新

componentWillReceiveProps(nextProps)

參數命名真的很重要,一看就知道他是傳入下一個props給這個function使用。就是當props被改變時會呼叫的。

但是要注意它有可能就算nextProps沒被改變,也會被呼叫
因為可能他的Parent物件重新render,導致他又收到(receive)了props,所以呼叫執行。

shouldComponentUpdate(nextProps, nextState)

有兩個參數,nextProps, nextState,這就是我昨天說“有可能不會re-render"的原因。你可以在這邊比較現在跟之前的props與state,去決定要不要更新Component。

記得要回傳bool沒寫的話預設是true,一定會更新

componentWillUpdate(nextProps, nextState)

即將更新囉,這個跟componentWillMount滿像的,但他可以根據State操作DOM
** shouldComponentUpdate return false就不會執行喔**

在這邊你就不要再setState了,不然看圖就知道,他會一直、一直、一直willUpdate。
這邊舉個例子,怎麼用它:

componentWillUpdate(nextProps, nextState) {
  if (nextState.open == true && this.state.open == false) {
    this.props.onWillOpen();
  }
}

你可以根據state轉換open/close狀態

 componentWillUpdate : function(newProps,newState){
    if(!newState.show){
        $(this.refs.elem).css({'opacity':'1'});
    }
    else{
      $(this.refs.elem).css({'opacity':'0'});;
    }
},

也可根據state改變css
更多資訊請參考:

  1. (https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/tapping_into_componentwillupdate.html)
  2. (http://stackoverflow.com/questions/33075063/what-is-the-exact-usage-of-componentwillupdate-in-reactjs/33075514#33075514)

接下來再render一次

componentDidUpdate(prevProps, prevState)

完成更新後執行,這邊也可以比較現在跟前一個props跟state,這邊跟componentDidMount一樣適合呼叫AJAX code。
** shouldComponentUpdate return false就不會執行喔**

這邊,是要destroy才會進行

componentWillUnmount()

清掉Timer跟request, 跟一些componentDidMount產生的DOM element。把建立出來的資源適時的收回,不會造成你的App越來越肥。

今天打滿快的,明天會有三種寫Component的方法,
各有各的好處,範例中也會常看到。
懂的怎麼轉換是很重要的喔!


上一篇
Day 12, React props and state 藏在component裡的變數
下一篇
Day 14, React components 各種寫Component的方法
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言