React Native填坑之旅 元件生命週期

2021-09-22 06:40:49 字數 2190 閱讀 5607

這次我們來填react native生命週期的坑。這一點非常重要,需要有乙個清晰的認識。如果你了解android或者ios的話,你會非常熟悉我們今天要說的的內容。

componentwillmount

componentwillmount():

void

元件開始渲染的時候呼叫這個方法

componentdidmount

componentdidmount():

void

元件的渲染完成之後呼叫這個方法。子元件的componentdidmount方法會在父元件的前面呼叫。componentwillmountcomponentdidmount方法之前呼叫,這個時候元件還沒有渲染完成。所以在componentwillmount裡呼叫setstate方法會立刻在render方法裡看到更新了的資料。

componentwillreceiveprops

componentwillreceiveprops(nextprops:

object):

void

當有新的props傳送給元件的時候,這個方法被觸發。最開始的render並不會呼叫這個方法! 使用這個方法可以在更新state,render方法被呼叫之前修改元件的props。在這個方法裡可以使用this.props來使用舊的props。在這個方法裡呼叫setstate方法不會觸發額外的render。

例如:

componentwillreceiveprops(nextprops) );

}

shouldcomponentupdate

shouldcomponentupdate(nextprops:

object

, nextstate:

object):

void

當收到新的props或者state的時候觸發這個方法。預設情況下shouldcomponentupdate一直返回true。這個方法在第一次render的時候不會呼叫。當你確定props和state被設定為新的值以後不需要元件更新的時候返回false。之後render方法在本次的更新中就會被直接跳過,componentwillupdatecomponentdidupdate兩個方法也不會被呼叫。

componentwillupdate

componentwillupdate(nextprops:

object

, nextstate:

object):

void

在props或者state更新之後立即呼叫這個方法。這個方法不會在第一次render的時候呼叫。

render

render(): reactelement<{}>

render方法被呼叫的時候,元件會根據新的this.propsthis.state繪製。render方法應該是乙個純方法。也就是說,它不修改元件的state,並且每次呼叫都返回相同的結果。當然,這個需要開發者來保證。

componentdidupdate

componentdidupdate(prevprops:

object

, prevstate:

object):

void

每次元件更新之後呼叫。第一次render的時候不會呼叫。

componentwillunmount():

void

元件被解除安裝之後呼叫。可以在這個方法裡執行一些清理操作。

React Native填坑之旅

解決方案 問題解決方案位址 sudo npm install g react devtools unsafe perm true in ios pods openssl universal ios lib libcrypto.a cryptlib.o building for ios simulat...

《Flex與Bison中文版》填坑之旅 2

fb1 5.tab.cpp 602 23 error yylex was not declared in this scope fb1 5.tab.cpp 1452 35 error yyerror was not declared in this scope 在兩個地方出現 所以,在fb1 5.y...

MySQL坑與填坑

錯誤 1064 錯誤 1215 原因 資料型別不同 錯誤 1630 去掉函式名和 間的空格 check 關鍵字無效 使用列舉或觸發器 特定字串約束 使用列舉 課程性質 char 10 constraint c5 check 課程性質in 公共基礎 專業基礎 專業選修 任意選修 課程性質 enum 公...