react 生命週期

2021-10-04 01:54:31 字數 1491 閱讀 7530

元件的生命週期可分成三個狀態:

mounting:已插入真實 dom

updating:正在被重新渲染

unmounting:已移出真實 dom

生命週期的方法有:

componentwillmount: 在渲染前呼叫,在客戶端也在服務端。

componentdidmount: 在第一次渲染後呼叫,只在客戶端。之後元件已經生成了對應的dom結構,可以通過this.getdomnode()來進行訪問。

componentwillreceiveprops: 在元件接收到乙個新的 prop (更新後)時被呼叫。這個方法在初始化render時不會被呼叫。

shouldcomponentupdate: 返回乙個布林值。在元件接收到新的props或者state時被呼叫。在初始化時或者使用forceupdate時不被呼叫。

可以在你確認不需要更新元件時使用。

componentwillupdate: 在元件接收到新的props或者state但還沒有render時被呼叫。在初始化時不會被呼叫。

componentdidupdate: 在元件完成更新後立即呼叫。在初始化時不會被呼叫。

componentwillunmount: 在元件從 dom 中移除之前立刻被呼叫。

import

react

,from

'react'

class

counter

extends

react

.component

console

.log

('元件初始化,設定state和獲取props')}

componentwillmount()

componentdidmount()

shouldcomponentupdate

(nextprops

,nextstate

)return

false

}componentwillupdate()

componentdidupdate()

componentwillunmount()

componentwillreceiveprops()

render()

=this

.state

;console

.count

('執行render方法'

)return

(<

button

onclick=)

}>

計數值:()

<

/button

>)}

}export

default

counter

;

React 生命週期 生命週期方法

生命週期 掛載 更新 解除安裝 元件被建立 執行初始化 並被掛載到dom中,完成元件的第一次渲染 constructor props getderivedstatefromprops props,state render componentdidmount 元件被建立時會首先呼叫元件的構造方法,接受...

react 生命週期

首次例項化 例項化完成後的更新 元件已存在時的狀態改變 生命週期共提供了10個不同的api。1.getdefaultprops 作用於元件類,只呼叫一次,返回物件用於設定預設的props,對於引用值,會在例項中共享。2.getinitialstate 作用於元件的例項,在例項建立時呼叫一次,用於初始...

react生命週期

盜圖一張 第一次進入頁面列印結果 1 parent constructor 2 parent conponentwillmount 3 parent render 4 initial render constructor 5 componentwillmount 6 render 7 compone...