iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
0
Modern Web

為期 30 天的 react 大冒險系列 第 22

react 大冒險-Lifecycle method-day 19

接續上篇,使用 promise 對 external api 取得值,
但如果想要在頁面讀取時就顯示出值,而不是等待使用者操作後才取值
就要靠 react 中的 lifecycle method


lifecycle method

還沒有 react hook 的時候,lifecycle method 僅 class component 可用
但隨 react hook 發展後,functional component 也發展出類似 class lifecycle 的部分
不過這裡只對 class component 的 lifecycle method 做說明

常用的 lifecycle method 有以下幾個

  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount

生命週期的不同階段 lifecycle stage

當 component 首次被建立時 (Mounting)

分別在 constructor / render / componentDidMount 內增加 console.log

可以明顯看到
依序執行的順序為

  1. constructor
  2. static getDerivedStateFromProps()
  3. render
  4. componentDidMount

component 被載入到 DOM 時 ,componentDidMount 便會自動執行


componentDidMount

因此,componentDidMount 就是最適合進行 api call對 DOM 做變更的位置
可以在這個階段中取得 api 的值,然後執行 setState,把取回的 value 設定為 state

如果是建立 component 時立刻 setState 而不需要取外部值時,在 constructor 內直接對 state 初始化就好
同樣的,也不要在 constructor 內 setState
一旦 componentDidMount 被執行完畢,直到下一次 component 被重新建立前,都不會再被執行
(只會執行一次)


當 component 被更新時 (Update)

component 會因以下三種情況發生而觸發

  1. component 接收到 new props
  2. 執行 setState更新 state
  3. 執行 this.forceUpdate

依序執行的順序為

  1. static getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate

如果 shouldComponentUpdate() 回傳 false,則 render 就不會被呼叫


getSnapshotBeforeUpdate

基本上用來代替舊版的 conponentWillUpdate
在 component 被更新後,如果需要使用更新前的 state 可以用這個方法

getSnapshotBeforeUpdate 可以 return null 或 return value
return 的值就是 componentDidUpdated 的第三個 parameter snapshot


什麼是 snapshot

可以是任何 data return from getSnapshotBeforeUpdate method
如果 component 內沒有 getSnapshotBeforeUpdate ,則 snapshot 的值就是 undefined


componentDidUpdated

componentDidUpdated 會在 component 被重新 render 後執行

另外 componentDidUpdate 可以接受三個 parameter prevProps / prevState / snapshot
這三個 parameter 會紀錄 update 前的 props (prevProps) 跟 state (prevState)

componentDidUpdate( prevProps,prevState,snapshot ){
    console.log('fired when component updates');
}

如果要在 componentDidUpdated 內 setState ** 務必要在 conditional statement 內執行
不然會導致
無限迴圈**產生


當 component 被移除時 (Unmount)

當 component 從 DOM 內被移除時,觸發 componentWillUnmount


回到上篇的範例

如果要在頁面載入時就發出 request 取值..增加 componentDidMount 這個 method
在 componentDidMount 裡面執行 getData,就可以取得最初 10 個名言了

改寫為

export default class GetData extends React.Component {
    constructor(props){
        ...
    }
    componentDidMount(){
        this.getData();
    }
    ...
}

補充資料


最後可以從這裡看到整個 lifecycle 的週期表


關於生命週期的官方文件
Understand React Lifecycle Methods


上一篇
react 大冒險-fetch data from API-day 18
下一篇
react 大冒險-higher order component-day 20-1
系列文
為期 30 天的 react 大冒險30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言