首页 > 技术文章 > react生命周期

hekeying 2021-05-11 18:00 原文

生命周期

组件初始化    创建时componentDidMount

组件更新        更新中componentDidUpdate

组件卸载       卸载时componentWillUnmount

 

// 自制 钟表

import React from 'react'

class Clock extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        date: new Date()
      }
    }
    componentDidMount() {
      this.timer = setInterval(() => {
        this.setState({
          date: new Date()
        })
      }, 1000)
    }
    // componentDidUpdate(currentProps, currentState) { // 接受2个参数 第一个参数 props  第二个参数 变化的值
    //   console.log(currentState)
    // }
    componentWillUnmount() {
      clearInterval(this.timer)
    }
    render() {
      return (
        <div className="jumbotorn">
          <h1>{ this.state.date.toLocaleTimeString() }</h1>
        </div>
      )
    }
}

export default Clock

推荐阅读