react中的生命週期函式
萬物皆有生命週期。 生命週期函式指在某一個時刻元件會自動執行的函式。 render constructor也可以理解為一個生命週期函式。在元件一建立的時刻,被自動的呼叫
1、initialzation 元件初始化的時候 (constructor的呼叫) 初始化資料 state and props 2、 Mounting 掛載 a. componentWillMount 在元件即將被掛載到頁面的時刻自動執行 b.render 內容渲染到頁面 c.componentDidMount 元件被掛載到頁面之後自動執行
componentWillMount和componentDidMount只在元件掛載的時候執行。各執行一次。元件掛載之後render函式可能多次執行(當資料發生改變時)
3、Updation 元件更新流程(資料發生變化時)
props發生變化時: a. componentWillReceiveProps —>states變化中沒有,二者唯一不同的差異 子元件將要接收屬性 // 當一個元件從父元件接收了引數 // 只有父元件的render函式重新被執行了。子元件的componentWillReceiveProps函式就會執行 如果這個元件第一次存在於父元件中,不會執行 如果這個元件之前已經存在於父元件中,才會執行
b.shouldComponentUpdate(){}
確認更新元件嗎
元件更新之前,會自動的執行.
返回一個布林值
,當為true
時,元件才會更新。可用於react元件的更新的效能優化
c. componentWillUpdate(){}
元件將要更新之前它會自動執行,但是在shouldComponentUpdate之後被執行,如果shouldComponentUpdate 返回false,它將不會執行。返回true才會執行。
d.render
重新渲染
e.componentDidUpdate
元件更新完成。
state發生變化時 1.shouldComponentUpdate 2.componentWillUpdate 3.render 4.componentDidUpdate
4、 Unmounting // 元件解除安裝之後 componetWillUnmount 元件將要從頁面中剔除的時候自動執行
生命週期函式的使用場景
1、當子元件不必要更新時,可用shouldComponentUpdate 返回false來提升程式碼效能
shouldComponentUpdate(nextProps, nextState)
接收nextProps
和nextState
2、非同步的獲取資料
在conponemtDidMunt中進行非同步資料獲取
提升react程式碼效能的方法
constructor (props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
2.在setState()中傳入函式,setState是一個非同步函式,它會把多次的資料改變合併成一次,降低虛擬dom的比對頻率。 3.藉助shouldComponetUpdate生命週期函式來避免元件不必要的虛擬dom比對和render渲染