componentDidMount()

အဲကောင်တွေ ဘယ်လိုအလုပ်လုပ်သွားလည်းဆိုတာကို ကျတော်တို့ တချက်ကြည့်လိုက်ကြရအောင်ဗျ

ကျတော်တို့အရင်ဆုံး ဒီလိုလေးရေးလိုက်ပါမယ်

import { Component } from 'react'

class LifeCycle extends Component {
    componentDidMount(){
        console.log("component life cycle start")
    }
    render(){
        return (
            <div>LifeCycle</div>
        )
    }
}
export default LifeCycle

ကျတော်တို့ အခုလက်ရှိသုံးထားတဲ့ componentDidMount() ဆိုတဲ့ method လေး က သူ့ name အတိုင်းပါပဲ

ကျတော်တို့ component လေးကို react ကနေပြီးတော့ Dom tree မှာ စတင်ပြီးတော့ create လုပ်လိုက်တာနဲ့

ဒီကောင်လေးက စတင်ပြီးတော့အလုပ်လုပ်ပေးပါတယ်

အဲဒီ method လေးက ဘာလို့အရေးကြီးတာလည်းဆိုတော့ ကျတော်တို့က browser ရဲ့ side effect

( api data fetching ) တွေကို အသုံးပြုချင်တဲ့အခါမှာ ပထမဦးဆုံးအကြိမ် fetch စေချင်တဲ့

အခါမျိုးမှာအသုံးပြုကြပါတယ်

အဲ method လေးက react ရဲ့ lifecycle ထဲမှာ ပထမဦးဆုံး တကြိမ်သာ အလုပ်လုပ်ပေးတာပါ

ကျန်တဲ့ အချိန် အခြေအနေ မှာ ပြန်ပြီးတော့အလုပ်မလုပ်ပေးပါဘူး

အဲဒီ method ထဲမှာ ကျတော်တို့ api request လေးတွေကို ခေါ်သုံးလို့ရပါတယ် အဲအတွက်

ကျတော်တို့ ဒီလိုလေး ရေးလိုက်ပါမယ်

class LifeCycle extends Component {
    getData = async() => {
        const data = await fetch("https://jsonplaceholder.typicode.com/users")
        const result = await data.json()
        console.log(result)
    }
    componentDidMount(){
        this.getData()
        console.log("component life cycle start")
    }
    render(){
        return (
            <div>LifeCycle</div>
        )
    }
}

ကျတော်တို့ က fetch ကိုအသုံးပြုပြီးတော့ ကျတော်တို့ web page ရဲ့ ပထမဆုံးအကြိမ် render ချလိုက်တဲ့

အချိန်မှာ data တွေကို fetch လုပ်လိုက်ပါတယ်

အဲဒါ ကို ကျတော်တို့ browser console မှာကြည့်ရင် ဒီလိုလေးတွေ့ရပါလိမ့်မယ်

ကျတော်တို့က componentDidMount က component မှာ ဦးဆုံးအလုပ်လုပ်ပေးတယ်လို့ ထင်နေပေမယ့်

တကယ်က သူက အရင်ဆုံး အလုပ်လုပ်မပေးပါဘူး

သူ့အရှေ့မှာ ဘာတွေအလုပ်လုပ်သေးတာလည်းဆိုတော့ constructor နဲ့ render က အလုပ်လုပ်ပေးပါတယ်

ပြီးတော့မှ သူက browser dom ပေါ်ကို ရောက်တော့မှ အလုပ်လုပ်ပေးတာပါ

class LifeCycle extends Component {
    constructor(){
        super()
        console.log("constructor start")
    }
    componentDidMount(){
        console.log("component life cycle start")
    }
    render(){
    console.log("render start")
        return (
            <div>LifeCycle</div>
        )
    }
}

အဲဒါကို ကြည့်လိုက်ရင် ကျတော်တို့ရဲ့ component lifecycle က ဘယ်အချိန်မှာ စတာလည်းဆိုတာကို မြင်သွား

မယ်လို့ ထင်ပါတယ်

အဲဒီလောက်ဆိုရင်တော့ ကျတော်တို့ရဲ့ lifecycle method တွေထဲ ပထမဆုံး တခုဖြစ်တဲ့

componentDidMount() ဆိုတဲ့ဟာလေးကို နားလည်သွားကြမယ်လို့ထင်ပါတယ်

နောက်တခု ကိုဆက်သွားကြရအောင်ဗျ

Last updated