react學(xué)習(xí)筆記-生命周期函數(shù)(4)

4-8、React中的生命周期函數(shù)

生命周期

生命周期函數(shù)指某一個時刻組件會自動調(diào)用執(zhí)行的函數(shù)

1)初始化(initialization)

初始化props and state中數(shù)據(jù)

2)掛載時(Mounting)

// 在組件即將被掛載到頁面的時刻自動執(zhí)行
componentWillMount() {
console.log('componentWillmount')
}
render () {
console.log('render')
}
// 在組件被掛載到頁面之后,自動執(zhí)行
componentDidMount() {
console.log('componentDidmount')
}

3)更新時(Updation)

// 在組件更新之前,它會自動被執(zhí)行
shouldComponentUpdate() {
console.log('shouldComponentUpdate')
return true
}
//組件被更新之前, 它會自動執(zhí)行,但是它在shouldComponentUpdate之后被執(zhí)行
// 如果shouldComponentUpdate返回true它才執(zhí)行
// 如果返回false,這個函數(shù)就不會執(zhí)行了
componentWillUpdate () {
console.log('componentWillUpdate')
}
// 組件更新完成之后會被執(zhí)行
componentDidUpdate () {
console.log('componentDidUpdate')
}

componentWillReceiveProps

//子組件中
// 1. 當(dāng)一個組件從父組件接收參數(shù)
// 2. 如果這個組件第一次存在于父組件中,不會被執(zhí)行
// 3. 如果這個組件之前已經(jīng)存在于父組件中,才會執(zhí)行
// 4. 滿足2,3情況下只要父組件的render函數(shù)被重新執(zhí)行了,子組件的這個生命周期函數(shù)就會被執(zhí)行
componentWillReceiveProps() {
console.log('child componentWillReceiveProps')
}

4)組件卸載時(Unmounting)

//子組件中
// 當(dāng)這個組件即將被從頁面中剔除的時候會執(zhí)行
componentWillUnmount () {
console.log('componentWillUnmount')
}

4-9、React生命周期的使用場景

避免子組件的重復(fù)執(zhí)行

shouldComponentUpdate (nextProps,nextState) {
if(nextProps.content !== this.props.content){
return true
} else{
return false
}
}
// 發(fā)送ajax請求數(shù)據(jù)
componentWillMount() {
// console.log('componentWillmount')
axios.get('/api/test').then(() => {
console.log('axios get')
}).catch((error) => {
console.log('error',error)
})
}

4-10、使用Charles實現(xiàn)本地數(shù)據(jù)mock

Charles——中間代理服務(wù)器

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 作為一個合格的開發(fā)者,不要只滿足于編寫了可以運行的代碼。而要了解代碼背后的工作原理;不要只滿足于自己的程序...
    六個周閱讀 8,686評論 1 33
  • 40、React 什么是React?React 是一個用于構(gòu)建用戶界面的框架(采用的是MVC模式):集中處理VIE...
    萌妹撒閱讀 1,196評論 0 1
  • 要講React的生命周期的話,網(wǎng)上講的已經(jīng)很過了,不過大多數(shù)是講react單個組件的生命周期,理論上組件本...
    周宇_6b69閱讀 1,599評論 0 0
  • 原教程內(nèi)容詳見精益 React 學(xué)習(xí)指南,這只是我在學(xué)習(xí)過程中的一些閱讀筆記,個人覺得該教程講解深入淺出,比目前大...
    leonaxiong閱讀 2,953評論 1 18
  • 坐在桌前,望著窗外黑黑的天空,似乎一場大雨即將光顧,但我沒有興奮和意外,因為天氣預(yù)報已經(jīng)提前通知了。 今天不知道寫...
    伊米crystal閱讀 655評論 2 3

友情鏈接更多精彩內(nèi)容