關於React v16 3 新生命週期

2021-09-24 07:21:01 字數 2519 閱讀 9550

react v16.3終於出來了,最大的變動莫過於生命週期去掉了以下三個

同時為了彌補失去上面三個週期的不足又加了兩個

當然,這個更替是緩慢的,在整個16版本裡都能無障礙的使用舊的三生命週期,但值得注意的是,舊的生命週期(unsafe)不能和新的生命週期同時出現在乙個元件,否則會報錯「你使用了乙個不安全的生命週期」。

舊的生命週期十分完整,基本可以捕捉到元件更新的每乙個state/props/ref,沒有什從邏輯上的毛病。

但是架不住官方自己搞事情,react打算在17版本推出新的async rendering,提出一種可被打斷的生命週期,而可以被打斷的階段正是實際dom掛載之前的虛擬dom構建階段,也就是要被去掉的三個生命週期。

生命週期一旦被打斷,下次恢復的時候又會再跑一次之前的生命週期,因此componentwillmount,componentwillreceiveprops, componentwillupdate都不能保證只在掛載/拿到props/狀態變化的時候重新整理一次了,所以這三個方法被標記為不安全。

class example extends react.component 

}複製**

返回乙個值,作為componentdidupdate的第三個引數。

配合componentdidupdate, 可以覆蓋componentwillupdate的所有用法。

class example extends react.component 

}複製**

初始化state — initializing state

請求資料 — fetching external data

新增事件監聽 — adding event listeners (or subscriptions)

根據props更新state — updating state based on props

if (this.props.currentrow !== nextprops.currentrow) 

複製**

取而代之的是,額外寫乙個state來記錄上乙個props (` ^ 『)

if (nextprops.currentrow !== prevstate.lastrow) ;

// 不更新state

return null

}複製**

觸發請求 — invoking external callbacks

props更新引起的*** — side effects on props change

// 在didupdate中根據props更新的確很不適應

// props變了也是可以觸發update的

componentdidupdate(prevprops, prevstate)

}複製**

props更新時重新請求 — fetching external data when props change

// old

componentwillreceiveprops(nextprops) );

this._loadasyncdata(nextprops.id);

}}複製**

// new

static getderivedstatefromprops(nextprops, prevstate) ;

}// no state update necessary

return null;

} componentdidupdate(prevprops, prevstate)

}複製**

在更新前記錄原來的dom節點屬性 — reading dom properties before an update

static getderivedstatefromprops(nextprops, prevstate) 

constructor

() componentwillmount

() componentdidmount

() componentwillreceiveprops

() shouldcomponentupdate

() componentwillupdate(nextprops, nextstate)

render

() getsnapshotbeforeupdate(prevprops, prevstate)

componentdidupdate(prevprops, prevstate, snapshot)

componentwillunmount

() 複製**

上面的內容基本就是結合我的一些經驗半翻譯半總結,有不準確的地方歡迎指正。

對更多細節感興趣的話可以去看官方文件,

對async-rendering或者對dan小哥哥感興趣的話可以去看看他在前端大會上的一段小演示:

關於海康(1)

一 安防行業介紹 二 海康核心技術 a 後端產品 dvr全球第一,嵌入式nvr全球第二。nvr是dvr以後才出來的產品,network video recorder 網路監控產品。業界說nvr是取代dvr的產品。長久以來,包括nvr在內的網路產品,因罩著網路這層神秘面紗 要設ip位址,要操作複雜的管...

關於跳槽 1

2015年的3月,我起了跳槽的心思。和同事姚 聊天談論跳槽的事情,總結了兩點 一是我對單位的未來前景不看好 二是換的新行業要有前景 今天在c114上看到乙個叫 瑞士軍刀 的牛人說 人在做選擇之前,先要問問 我是誰?在這裡我就問一下我自己 我是誰?我是乙個規規矩矩讀書,本本分分應試,僥倖順利碩士畢業,...

關於快取1

1.想寫關於快取的起因 最近在做de乙個企業的官網,之前做手機端網頁,p2p 時都出現過修改頁面,手機電腦重新整理沒有效果。2.什麼是瀏覽器快取 3.怎樣判斷請求是從伺服器獲取還是使用快取 開啟f12開發者工具network,再次重新整理頁面看網路請求,size一列對應的是from cache則是從...