React v16 3新生命週期

2021-08-20 06:22:35 字數 2607 閱讀 4301

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

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

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

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

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

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

每次接收新的props之後都會返回乙個物件作為新的state,返回null則說明不需要更新state.

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

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小哥哥感興趣的話可以去看看他在前端大會上的一段小演示:

關於React v16 3 新生命週期

react v16.3終於出來了,最大的變動莫過於生命週期去掉了以下三個 同時為了彌補失去上面三個週期的不足又加了兩個 當然,這個更替是緩慢的,在整個16版本裡都能無障礙的使用舊的三生命週期,但值得注意的是,舊的生命週期 unsafe 不能和新的生命週期同時出現在乙個元件,否則會報錯 你使用了乙個不...

解讀 React v16 最新生命週期使用場景

react更新到v16版本之後,像是跨入了新的時代,效能和新的api都令人矚目,所以出現了比較大的生命週期方法調整,包括使用方法和使用場景,本章節針對新舊的生命週期的使用方法及使用場景分別詳細介紹描述總結 在介紹生命週期之前,我們首先需要搞清楚react生命週期的幾個階段 從上面幾個生命期可以發現,...

Reactv16 8 6生命週期函式

react 主動呼叫的方法,也可重寫這些方法 生命週期圖譜 constructor props 如果不需要初始化 state 或 不進行方法繫結,則不需要使用該方法 在元件掛載之前會先呼叫該方法,在實現建構函式時必須先呼叫super props 方法,否則會出現bug 通常,建構函式僅用於兩種情況 ...