iT邦幫忙

0

React 元件的生命周期:

React 元件的生命周期:

只講常用的:

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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言