生命週期:掛載、更新、解除安裝
【元件被建立、執行初始化、並被掛載到dom中,完成元件的第一次渲染】
constructor(props)
getderivedstatefromprops(props, state)
render()
componentdidmount()
元件被建立時會首先呼叫元件的構造方法,接受乙個props。
呼叫super(props)才能保證props被傳入元件。
通常用於初始化元件的state及繫結事件處理方法
(2)getderivedstatefromprops(props, state)
呼叫render方法之前呼叫,並且再初始掛載及後續更新時都會被呼叫
返回乙個物件來更新state,如果返回null則不更新內容
不管原因是什麼,都會在每次渲染前觸發此方法
用於描述元件的ui,並不負責元件的實際渲染工作。
只返回乙個ui的描述,真正渲染出頁面dom的工作由react自身負責。
不能執行任何有***的操作,比如this.setstate
被掛載到dom後呼叫,且只會被呼叫一次。
通常用於向伺服器請求資料,呼叫this.setstate會引起元件的重新渲染
【無論props是否改變,父元件render方法每一次呼叫,都會導致元件更新。
呼叫this.setstate修改元件state也會觸發元件更新】
static getderivedstatefromprops(props, state)
shouldcomponentupdate(nextprops, nextstate)
render()
getsnapshotbeforeupdate(preprops,prestate)
componentdidupdate(preprops,prestate)
(1)static getderivedstatefromprops(props, state)
(2)shouldcomponentupdate(nextprops, nextstate)
決定元件是否繼續執行更新
當方法返回true(預設值)時,元件會繼續更新,返回false時,元件停止更新。
(3)render()
(4)getsnapshotbeforeupdate(preprops,prestate)
使元件能在發生更新前從dom中捕獲一些資訊(例如滾動位置)
返回值將作為引數傳遞給componentdidupdate()
(5)componentdidupdate(preprops,prestate,snapshot)
元件更新後呼叫,preprops,prestate代表元件更新前的props和state
元件被解除安裝前呼叫,可以執行一些清理工作
參考:
react生命週期方法
每乙個元件都有幾個你可以重寫以讓 在處理環節的特定時期執行的 生命週期方法 方法中帶有字首will的在特定環節之前被呼叫,而帶有字首did的方法則會在特定環節之後被呼叫。react生命週期可分為三個狀態以及對應的方法 mounting 裝配 react元件的建構函式將會在裝配之前被呼叫。在渲染前呼叫...
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...