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 負責。
 
![[筆記]Vim 01 - 編輯+基本語法](https://static.coderbridge.com/images/covers/default-post-cover-1.jpg)

