iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 7
0
自我挑戰組

請你當我的好朋友吧!ReactJS!系列 第 7

【DAY 07】React Component也有生老病死?(上)

【前言】
  昨天講完Refs,會不會覺得目前React已經很煩了呢?希望你不會......XD

【正文】
  今天要來聊聊React Component的生命週期(Lifecycle),首先React Component的生命週期一定是class宣告的Component才會有的方法,而生命週期顧名思義,Component本身也會有掛載、更新、結束階段。那今天的練習會用到componentDidMount()componentWillUnmount()這兩個方法。

  •   componentDidMount()
      1. Component已經render到實體DOM階段完成的時候觸發
      2. 此method只會被呼叫一次
      3. 在這裡可以setState(),並會再次重新render component一次
      4. 可以放入具有side effect的function,如setInterval、呼叫API等等

  •   componentWillUnmount()
      1.  Component即將從實體DOM階段移除「之前」的時候觸發
      2.  也是只會被呼叫一次
      3.  可以在這裡使用setState()
      4.  也可以放入具有side effect的function

  大致理解上面這兩個lifecycle methods之後,大家是否還記得之前在講state做的時鐘練習吧?那時候我們是用按一個按鈕觸發更新時間,今天我們就再來修改這隻程式碼,讓他可以自動更新時間吧!


App.js

import React from 'react';

class App extends React.Component {
  // 在建構子設定state的初始值
  constructor(props) {
    super(props);
    this.state = {
      currentTime: new Date().toLocaleString(),
    };
  }

  // 在Component render到真實DOM中,使用ComponentDidMount,
  // 並在裡面使用setInterVal,並將回傳的計時器id存放在timerId中
  componentDidMount() {
    this.timerId = setInterval( this.updateTime, 1000);
  }

  // 在component即將從真實DOM中移除之前,使用componentWillUnmount
  // 使用clearInterval把timerId移除掉
  componentWillUnmount() {
    clearInterval(this.timerId);
  }

  // 宣告update時間的方法
  updateTime = () => {
    this.setState({
      currentTime: new Date().toLocaleString(),
    })
  }

  render() {
    const { currentTime } = this.state;
    return ( 
      <div style = {{ textAlign: 'center' }} >
        <div>{currentTime}</div>
      </div>
    );
  }
}

export default App;

  執行結果的畫面長這樣:
執行結果
  燈燈!!是不是可以自動更新時間了呢?你看今天就會使用兩種的lifecycle method囉,但React不僅僅只提供這兩種,還有其他可以用的方法,那就等明天的時候再來慢慢分享其他的吧!


上一篇
【DAY 06】React!還有?refs你別來好不?
下一篇
【DAY 08】React Component也有生老病死?(下)
系列文
請你當我的好朋友吧!ReactJS!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言