React的生命週期:算法
constuctor:後端
1、組件的初始化,用來定義當前組件所須要的一些狀態,狀態定義在this.state中。緩存
2、當前生命週期中必須書寫super,不然this的指向會發生錯誤以及報錯性能優化
3、在當前生命週期中默認是訪問不到props屬性的,若是想要進行訪問必須在super以及constructor中添加參數propsdom
componentWillMount:函數
掛載前:性能
1、能夠進行先後端數據的請求(在服務端渲染的時候)優化
2、能夠在數據第一次被渲染的時候作數據的更改this
3、在當前生命週期中儘可能不要調用this.setState由於當前生命週期函數執行完畢後,會自動執行render函數spa
4、能夠將外部的數據轉換爲內部的數據
注意:當前生命週期在17.0中已經廢除掉了
render:
1、當前生命週期用來進行數據與模板的結合
2、render函數第一次執行的時候會將渲染的數據在內存中保存一份,當第二次數據發生了改變後,render會將此次的虛擬DOM與緩存中的虛擬DOM進行對比 這種對比叫作DIFF算法
3、只要this.state/this.props發生了改變那麼render函數就會執行
componentDidMount:
掛載後:
1、當前生命週期咱們能夠作先後端數據的交互
2、能夠在當前生命週期中獲取到真實的DOM 經過this.refs來獲取
3、通常狀況下咱們都在當前生命週期中作一些插件的實例化
new Swiper('')
操做真實DOM的方式
ref="h2" this.refs.h2
ref={(el)=>{this.dom = el}} this.dom
componentwillReceiveProps(newProps):
1、當this.props發生改變的時候當前函數就會執行
2、當前函數中會有一個參數 這個參數是一個新的props
3、在當前生命週期函數中咱們能夠對新的props作修改
4、當前生命週期函數在17.0中廢除掉了
shouldComponentUpdate(newProps,newState):
1、當this.state/this.props被修改的時候會執行當前生命週期函數
2、當前生命週期執行的時候必須返回一個true或者是false 返回值決定了render函數是否會執行,若是爲true則render函數執行false則render函數不會執行
3、若是返回值爲true則下面的生命週期會執行,若是爲false則下面的生命週期不會執行
4、當前生命週期特別重要,由於當前生命能夠作React的性能優化,(根據比較新舊的state/props來進行對比)
5、當前生命週期函數中有2個參數一個是新的props 一個是新的state
6、當期生命週期決定的是render函數是否執行,而不是數據是否修改
componentWillUpdate(newProps,newState):
更新前:
1、在當前生命週期中咱們能夠對更新的數據作最後的修改
2、當前生命週期中有2個參數 一個是新的props一個是新的state
注意:當前生命週期在17.0中已經廢除掉了
componentDidUpdate:
更新後
1、當前生命週期中咱們能夠獲取到數據更新後最新的DOM結構
2、注意當前生命週期會執行屢次,因此當你須要作業務邏輯操做的時候必定要判斷
componentWillUnmount:
卸載
1、當前生命週期執行的時候咱們須要作事件的解綁
2、數據的移除等操做
總結:
在第一次渲染時執行的周期函數有:
Constructor;componentWillMount;render;componentDidMount
當this.props/this.state發生改變的時候執行的生命週期:
this.props
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
this.state
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
React中哪些生命週期會執行一次,哪些生命週期會執行屢次
屢次
componentWillReceiveProps;shouldComponentUpdate;componentWillUpdate
render;componentDidUpdate
一次
constructor;componentWillMount;componentDidMount
componentWillUnmount
在17版本中廢除的生命週期有(componentWillMount,componentwillReceiveProps,componentWillUpdate),與之增長的生命週期有:
getDerivedStateFromProps(nextProps, prevState):
一、根據傳入的 props 來更新 state
二、該方法是一個 static 方法意味着這個方法是屬於 React.Component 類的方法,因此方法內是沒法使用 this 的,這就意味着沒法使用 this.setState 來更新 state,因此這個方法直接經過返回對象的形式來更新 state,若是某些 props 的狀況不須要更新 state,那麼就返回 null 就好。實際上這個方法和 componentDidUpdate 搭配使用,就能覆蓋 componentWillReceiveProps 的全部使用場景了
一、在更新以前獲取組件的快照,在組件更新前觸發
二、它的返回值會做爲第三個參數傳遞給後面的 componentDidUpdate 參數中,和 componentDidUpdate 一塊兒使用,能覆蓋掉 componentWillUpdate 的全部使用場景了
componendDidCatch(error, info)
若是一個組件定義了componentDidCatch生命週期,則他將成爲一個錯誤邊界(錯誤邊界會捕捉渲染期間、在生命週期方法中和在它們之下整棵樹的構造函數中的錯誤,
就像使用了try catch,不會將錯誤直接拋出了,保證應用的可用性)