關於 React 小書:實作 Clock 並簡介 component lifecycle 裡各個階段的作用


Posted by YongChenSu on 2020-12-09

Clock

/* 
  componentWillMount, componentDidMount, componentWillUnmount
  在 component lifecycle 中有什麼作用
*/
import React, { Component} from 'react'
import ReactDOM from 'react-dom'
import './index.css'

class Clock extends Component {
  constructor () {
    super()
    this.state = {
      date: new Date()
    }
  }

  componentWillMount() {
    this.timer = setInterval(() => {
      this.setState({ date: new Date() })
    }, 1000)
  }

  componentWillUnmount () {
    clearInterval(this.timer)
  }

  render() {
    return (
      <div>
        <h1>
          <p>現在時間是</p>
          {this.state.date.toLocaleTimeString()}
        </h1>
      </div>
    )
  }
}

class Index extends Component {
  constructor () {
    super()
    this.state = { isShowClock: true }
  }

  handleShowOrHide () {
    this.setState({
      isShowClock: !this.state.isShowClock
    })
  }

  render () {
    return (
      <div>
        {this.state.isShowClock ? <Clock /> : null }
        <button onClick={this.handleShowOrHide.bind(this)}>
          Show or Hide
        </button>
      </div>
    )
  }
}

ReactDOM.render(
  <Index />,
  document.getElementById('root')
)


componentWillUnmount 作用

若隱藏 Clock 的時候沒有清除定時器,仍會不斷 setState,故利用 componentWillUnmount 清理數據。

總結

  • componentWillMount:一般會把 component 的 state 的初始化工作放在 constructor 裡面,在 componentWillMount 進行 Component 的啟動。
  • componentWillUnMount:清理數據,例如清理非同步的請求(定時器)。
  • componentDidMount:有些 Component 的啟動是依賴 DOM 的,例如畫面的啟動,故這由 componentDidMount 負責。

參考資源


#程式導師實驗計畫第四期 #前端 #React #react 小書







Related Posts

利用 jest 寫測試

利用 jest 寫測試

197. Rising Temperature

197. Rising Temperature

Some relative page about the "dependent types"

Some relative page about the "dependent types"


Comments