React學習 二 React生命週期

2021-09-27 03:45:01 字數 2228 閱讀 5968

工作中發現在使用react元件時會出現先後順序的問題,也就是在乙個元件的整個生命週期中,通過使用者的互動來更新state或者props,重新渲染元件,更新頁面的ui。組成乙個簡單的「狀態機」。

1、 constructor()構造方法

constructor是es6對類的預設方法,通過 new命令生成物件例項時自動呼叫該方法。初始化執行一次。使用constructor必須手動呼叫super方法。需要呼叫this.props必須傳入props。比如

class

classname

extends

react.component

;// 在constructor中可以初始化state

this

.state =

;// !這種操作是錯誤的,應該避免,任何對state的操作除了初始化都要使用setstate方法

this

.setstate()

;//應該使用這種方法

this

.handleclick =

this

.handleclick.

bind

(this);

// 將事件處理方法繫結到例項。

}

state =

;// 也可以直接初始化state

}

2、 componentwillmount => unsafe_componentwillmount()(即將被廢棄)

首次渲染(render)之前呼叫,只執行一次。呼叫setstate方法,是渲染之前最後更改state的最後機會。一般來說不會用,但是也是可以用的。哈哈哈

3、render元件渲染

這個方法會建立乙個虛擬dom,用來表示元件的輸出。對於乙個元件來講,render方法是唯一乙個必需的方法。state或者props的更新都會引起render的重渲染,會多次執行。

該方法只能返回乙個頂級元件,或者返回false/null;在這裡也不能修改元件的狀態,即不可呼叫setstate方法。

render方法返回的結果並不是真正的dom元素,而是乙個虛擬的表現,類似於乙個dom tree的結構的物件。react之所以效率高,就是這個原因。

4、componentdidmount

元件渲染完成後呼叫該方法,只執行一次。在這裡已經渲染出真實的dom節點了,可以再該方法中通過 this.getdomnode() (新版本已被棄用,推薦使用reactdom.finddomnode)訪問到真實的 dom。

該方法中也可以呼叫setstate來更新狀態重新渲染元件,這裡也是設定定時器監聽事件的好地方。

1、componentwillreceiveprops(nextprops) => unsafe_componentwillreceiveprops(nextprops)(即將被廢棄)

元件props發生改變會呼叫該方法(或者說只要父元件更新,不管props是否與以前相同,都會呼叫該方法), 接收乙個引數nextprops,所以在這裡可以繼續拿到this.props的值。在這個方法中更新state是安全的,一般情況下為了避免任何props的改變多次觸發state更新,

可以通過nextprops和this.props的比較後再做相關操作。

2、static getderivedstatefromprops(props, state)(新)

3、 shouldcomponentupdate(nextprops, nextstate)

通過返回true或者false來判斷是否需要重新渲染元件。如果返回false,後面的ender 以及 componentwillupdate,componentdidupdate 方法都將不會執行。元件比較多時,使用該方法能夠避免不需要的重渲染,優化效能。

class

classname

extends

react.component

;// 在constructor中可以初始化state

}componentdidmount()

shouldcomponentupdate:

function

(nextprops, nextstate)

render()

}

componentwillunmount

該方法將會在 component 從dom中移除時呼叫。一些元件相關的清理工作都可以在這裡處理。

目前就接觸到這些

react學習筆記 react生命週期

react v16.4 的生命週期 提前感謝aermin的筆記詳解react生命週期 包括react16版 讓我收益匪淺。我通常把react生命週期劃分為四個階段 元件初始化,元件掛載,元件更新,元件解除安裝。import react,from react class test extends co...

React入門(二) React元件的生命週期

componentwillmount componentdidmount componentwillunmount componentwillupdate componentdidupdate shouldcomponentupdate componentwillreceiveprops react...

React學習筆記 生命週期

constructor props 初始化方法。object getinitialstate 獲取初始state。void componentwillmount render之前執行一次。reactelement render 渲染檢視。void componentdidmount 初始化rande...