iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0
自我挑戰組

React基礎系列 第 9

第九天,React 元件的生命周期:

React 元件的生命周期:

這是用console.log跑程式所出來的順序,數字是記錄而已。

1.constructor:初始化
4.render:在網頁上輸出元件內容
2.componentDidMount:輸出後會執行的函數。
若在componentDidMount中state的內容有被改變,就輸出以下的值。
4.render
3.componentDidUpdate:只要state有變動,就會執行這個函數。
4.render
3.componentDidUpdate
4.3.4.3.4.3.4.3.4.3.4.3.4......

import React, { Component } from 'react';

class LifeCycle extends Component{
    constructor(props){
        super(props);
        this.state={time : new Date().toLocaleTimeString()}
        console.log("1.constructor");
    }
    //元件產生後首先執行的動作
    componentDidMount(){
        console.log("2.componentDidMount");
        this.setState({time : new Date().toLocaleTimeString()})
    }
    componentDidUpdate(){
        console.log("3.componentDidUpdate");
        const upTime = () =>{
            //這裡面的setState()能夠重新設定state的值
            this.setState({time : new Date().toLocaleTimeString()})
        }
        setInterval(upTime,10000);
    }

    render(){
        console.log("4.render");
        return <h1>現在時間是{this.state.time}</h1>
    }
}

export default LifeCycle;
參考資料:https://ithelp.ithome.com.tw/articles/10200767


上一篇
第八天,React圖文元件,重覆使用
下一篇
第10天,React三種使用CSS方法
系列文
React基礎12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言