React中生命週期鉤子函式例項演示

2021-10-07 15:46:11 字數 2045 閱讀 5462

# react生命週期鉤子函式

## 頁面渲染期

* constructor 建構函式 在所有函式執行之前它先執行(資料接收 實現繼承super(props))

* unsafe_componentwillmount 元件將要掛載(資料掛載之前 可以運算元據 不可以操作dom)

* render 頁面渲染(渲染元件 和 html 標籤)

* componentdidmount 元件掛載完成(資料掛載之後 可以運算元據和dom)

## 頁面更新期

* unsafe_componentwillreceiveprops 父元件上狀態變化時 會自動觸發鉤子函式 子元件可以由此決定是否接收資料(接收元件傳入輸入資料)

* shouldcomponentupdate 元件是否要更新資料,需要返回布林值 true 跟新資料 false 不更新資料(檢測元件內的變化 可以用作頁面效能的優化(預設值為true))

* unsafe_componentwillupdate 元件更新資料(元件更新之前呼叫)

* render 頁面從新渲染(元件更新之後渲染元件)

* componentdidupdate 元件資料更新完成(元件更新之後呼叫)

## 頁面銷毀期

* componentwillunmount 頁面銷毀(元件銷毀時呼叫 可以做一些記憶體的優化 [全域性變數,閉包,計時器,事件])

只有類元件才有生命週期,函式元件沒有生命週期

// 父元件

import react, from 'react'

import child from './child'

// 鉤子函式執行順序和編寫順序無關

export default class parent extends component

console.log('建構函式執行了-constructor...')

}// 嚴格模式下 不建議使用

unsafe_componentwillmount()

render()

/>

this.setstate() }>銷毀)}

componentdidmount()

// 頁面更新期

shouldcomponentupdate()

unsafe_componentwillupdate()

msgchange(e))

}// 還有個 render鉤子函式 頁面渲染

componentdidupdate()

}

// 子元件

import react, from 'react'

export default class child extends component

render() )}

unsafe_componentwillmount()

componentdidmount()

// 更新期

shouldcomponentupdate()

unsafe_componentwillupdate()

componentdidupdate()

// 放子元件 會自動執行 放父元件不會自動執行

unsafe_componentwillreceiveprops()

// 頁面銷毀期

React生命週期鉤子函式

定義 react中元件有生命週期,也就是說也有很多鉤子函式供我們使用,元件的生命週期,我們會分為四個階段,初始化 執行中 銷毀 錯誤處理 16.3之後 注意 生命週期鉤子函式一定不要寫成箭頭函式 react 16.x 版本中共有 10個鉤子函式 四個階段 分別為 1 constructor prop...

React的生命週期鉤子函式

一 react的生命週期鉤子函式舊版 掛載時,初始化階段 1 constructor 如果不初始化state或不進行方法繫結,則不需要為react元件實現建構函式 2 componentwillmount 以前在這裡進行請求資料,現在即將被廢棄 3 render 初次渲染元件的內容 4 compon...

react生命週期的鉤子函式

生命週期,鉤子函式 掛載階段 一 constructor 第乙個執行 1.可以初始化元件狀態 2.可以給一些事件函式繫結this 注意 不能再內部呼叫setstate constructor 不能在內部呼叫setstate this.handleclick this.handleclick.bind...