好程式設計師web前端培訓分享React學習筆記(三)

好程式設計師發表於2020-04-27

   好程式設計師web 前端培訓分享 React 學習筆記(三) 元件的生命週期

   React 中元件也有生命週期,也就是說也有很多鉤子函式供我們使用 , 元件的生命週期,我們會分為四個階段,初始化、執行中、銷燬、錯誤處理 (16.3 之後 )

初始化

在元件初始化階段會執行

00001.  constructor

00002.  static getDerivedStateFromProps()

00003.  componentWillMount() / UNSAFE_componentWillMount()

00004.  render()

00005.  componentDidMount()

更新階段

props state 的改變可能會引起元件的更新,元件重新渲染的過程中會呼叫以下方法:

00001.  componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()

00002.  static getDerivedStateFromProps()

00003.  shouldComponentUpdate()

00004.  componentWillUpdate() / UNSAFE_componentWillUpdate()

00005.  render()

00006.  getSnapshotBeforeUpdate()

00007.  componentDidUpdate()

解除安裝階段

00001.  componentWillUnmount()

錯誤處理

00001.  componentDidCatch()

各生命週期詳解

1.constructor(props)

React元件的建構函式在掛載之前被呼叫。在實現 React.Component 建構函式時,需要先在新增其他內容前,呼叫 super(props) ,用來將父元件傳來的 props 繫結到這個類中,使用 this.props 將會得到。

官方建議不要在 constructor 引入任何具有副作用和訂閱功能的程式碼,這些應當使用 componentDidMount()

constructor 中應當做些初始化的動作,如:初始化 state ,將事件處理函式繫結到類例項上,但也不要使用 setState() 。如果沒有必要初始化state或繫結方法,則不需要構造 constructor ,或者把這個元件換成純函式寫法。

當然也可以利用 props 初始化 state ,在之後修改 state 不會對 props 造成任何修改,但仍然建議大家提升狀態到父元件中,或使用 redux 統一進行狀態管理。

constructor(props)   {

   super (props);

   this .state   =   {

     isLiked :   props.isLiked

   };}

2.static getDerivedStateFromProps(nextProps, prevState)

getDerivedStateFromProps  是react16.3之後新增,在元件例項化後,和接受新的 props 後被呼叫。他必須返回一個物件來更新狀態,或者返回null表示新的props不需要任何state的更新。

如果是由於父元件的 props 更改,所帶來的重新渲染,也會觸發此方法。

呼叫 steState() 不會觸發 getDerivedStateFromProps()

之前這裡都是使用 constructor + componentWillRecieveProps 完成相同的功能的

3. componentWillMount() / UNSAFE_componentWillMount()

componentWillMount() 將在React未來版本(官方說法 17.0)中被棄用。 UNSAFE_componentWillMount() 在元件掛載前被呼叫,在這個方法中呼叫 setState() 不會起作用,是由於他在 render() 前被呼叫。

為了避免副作用和其他的訂閱,官方都建議使用 componentDidMount() 代替。這個方法是用於在伺服器渲染上的唯一方法。這個方法因為是在渲染之前被呼叫,也是惟一一個可以直接同步修改state的地方。

4.render()

render()方法是必需的。當他被呼叫時,他將計算 this.props this.state ,並返回以下一種型別:

00001.  React元素。透過jsx建立,既可以是dom元素,也可以是使用者自定義的元件。

00002.  字串或數字。他們將會以文字節點形式渲染到dom中。

00003.  Portals。react 16版本中提出的新的解決方案,可以使元件脫離父元件層級直接掛載在DOM樹的任何位置。

00004.  null,什麼也不渲染

00005.  布林值。也是什麼都不渲染。

當返回 null , false , ReactDOM.findDOMNode(this) 將會返回null,什麼都不會渲染。

render() 方法必須是一個純函式,他不應該改變 state ,也不能直接和瀏覽器進行互動,應該將事件放在其他生命週期函式中。 如果 shouldComponentUpdate() 返回 false render() 不會被呼叫。

5. componentDidMount

componentDidMount 在元件被裝配後立即呼叫。初始化使得DOM節點應該進行到這裡。

通常在這裡進行ajax請求

如果要初始化第三方的dom庫,也在這裡進行初始化。只有到這裡才能獲取到真實的dom.

6.componentWillReceiveProps()/UNSAFE_componentWillReceiveProps(nextProps)

官方建議使用 getDerivedStateFromProps 函式代替 componentWillReceiveProps 。當元件掛載後,接收到新的 props 後會被呼叫。如果需要更新 state 來響應 props 的更改,則可以進行 this.props nextProps 的比較,並在此方法中使用 this.setState()

如果父元件會讓這個元件重新渲染,即使 props 沒有改變,也會呼叫這個方法。

React不會在元件初始化props時呼叫這個方法。呼叫 this.setState 也不會觸發。

7.shouldComponentUpdate(nextProps, nextState)

呼叫 shouldComponentUpdate 使React知道,元件的輸出是否受 state props 的影響。預設每個狀態的更改都會重新渲染,大多數情況下應該保持這個預設行為。

在渲染新的 props state 前, shouldComponentUpdate 會被呼叫。預設為 true 。這個方法不會在初始化時被呼叫,也不會在 forceUpdate() 時被呼叫。返回 false 不會阻止子元件在 state 更改時重新渲染。

如果 shouldComponentUpdate() 返回 false componentWillUpdate , render componentDidUpdate 不會被呼叫。

官方並不建議在 shouldComponentUpdate() 中進行深度查詢或使用 JSON.stringify() ,他效率非常低,並且損傷效能。

8.UNSAFE_componentWillUpdate(nextProps, nextState)

在渲染新的 state props 時, UNSAFE_componentWillUpdate 會被呼叫,將此作為在更新發生之前進行準備的機會。這個方法不會在初始化時被呼叫。

不能在這裡使用this.setState() ,也不能做會觸發檢視更新的操作。如果需要更新 state props ,呼叫 getDerivedStateFromProps

9.getSnapshotBeforeUpdate()

react  render() 後的輸出被渲染到DOM之前被呼叫。它使您的元件能夠在它們被潛在更改之前捕獲當前值(如滾動位置)。這個生命週期返回的任何值都將作為引數傳遞給componentDidUpdate()。

10.componentDidUpdate(prevProps, prevState, snapshot)

在更新發生後立即呼叫 componentDidUpdate() 。此方法不用於初始渲染。當元件更新時,將此作為一個機會來操作DOM。只要您將當前的props與以前的props進行比較(例如,如果props沒有改變,則可能不需要網路請求),這也是做網路請求的好地方。

如果元件實現 getSnapshotBeforeUpdate() 生命週期,則它返回的值將作為第三個“快照”引數傳遞給 componentDidUpdate() 。否則,這個引數是 undefined

11.componentWillUnmount()

在元件被解除安裝並銷燬之前立即被呼叫。在此方法中執行任何必要的清理,例如使定時器無效,取消網路請求或清理在 componentDidMount 中建立的任何監聽。

12.componentDidCatch(error, info)

錯誤邊界是React元件,可以在其子元件樹中的任何位置捕獲JavaScript錯誤,記錄這些錯誤並顯示回退UI,而不是崩潰的元件樹。錯誤邊界在渲染期間,生命週期方法以及整個樹下的建構函式中捕獲錯誤。

如果類元件定義了此生命週期方法,則它將成錯誤邊界。在它中呼叫 setState() 可以讓你在下面的樹中捕獲未處理的JavaScript錯誤,並顯示一個後備UI。只能使用錯誤邊界從意外異常中恢復; 不要試圖將它們用於控制流程。

錯誤邊界只會捕獲樹中下面元件中的錯誤。錯誤邊界本身不能捕獲錯誤。

PureComponent

PureComponnet 裡如果接收到的新屬性或者是更改後的狀態和原屬性、原狀態相同的話,就不會去重新render了 在裡面也可以使用 shouldComponentUpdate ,而且。是否重新渲染以 shouldComponentUpdate 的返回值為最終的決定因素。

import React, { PureComponent } from 'react'

class YourComponent extends PureComponent {

  ……

}

ref

React提供的這個 ref 屬性,表示為對元件真正例項的引用,其實就是 ReactDOM.render() 返回的元件例項, ref 可以掛載到元件上也可以是dom元素上。

·  掛到元件( class 宣告的元件)上的ref表示對元件例項的引用。 不能 在函式式元件上使用 ref 屬性,因為它們沒有例項:

·  掛載到dom元素上時表示具體的dom元素節點。

React 最新的版本中,要使用 ref , 需要使用 React.createRef 方法先生成一個 ref

import   React,   {   Component,   createRef   }   from   'react' import   ReactDOM   from   'react-dom' class   App   extends   Component   {

   constructor()   {

     super ()

     // 建立inputRef      this .inputRef = createRef()

   }

   componentDidMount   ()   {

     console.log( this .inputRef.current)   // <input type="text">    }

   render   ()   {

     return   (

         < div >

         { /* 關聯ref和dom */ }

         < input   type = "text"   ref = { this .inputRef}   />

       < /div>

     )

   }}ReactDOM.render(

     < App /> ,

   document .getElementById( 'root' ))

React Hooks

React Hooks 是 React  16.7.0-alpha  版本推出的新特性, 有了React Hooks,在 react 函式元件中,也可以使用類元件(classes components)的 state 和 元件生命週期。透過下面幾個例子來學習React Hooks。

·  State Hook

// useState是react包提供的一個方法 import   React,   {   useState   }   from   "react" ; import   ReactDOM   from   "react-dom" ; const   Counter   =   ()   =>   {

   // useState 這個方法可以為我們的函式元件擁有自己的state,它接收一個用於初始 state 的值,返回一對變數。這裡我們把計數器的初始值設定為0, 方法都是以set開始    const   [count,   setCount]   =   useState( 0 );

   return   (

     < div >

       < p > 你點選了{count}次 < /p>

       < button   onClick = {()   =>   setCount(count   +   1 )} > 點選 < /button>

     < /div>

   );}; const   rootElement   =   document .getElementById( "root" ); ReactDOM.render( < Counter   /> ,   rootElement);

·  Effect Hook

// useState是react包提供的一個方法 import   React,   {   useState,   useEffect   }   from   "react" ; import   ReactDOM   from   "react-dom" ; const   Counter   =   ()   =>   {

   // useState 這個方法可以為我們的函式元件擁有自己的state,它接收一個用於初始 state 的值,返回一對變數。這裡我們把計數器的初始值設定為0, 方法都是以set開始    const   [count,   setCount]   =   useState( 0 );

   // 類似於componentDidMount或者componentDidUpdate:    useEffect(()   =>   {

     // 更改網頁的標題,還可以做其它的監聽      document .title   =   `你點選了${ count }次` ;

   });

   return   (

     < div >

       < p > 你點選了{count}次 < /p>

       < button   onClick = {()   =>   setCount(count   +   1 )} > 點選 < /button>

     < /div>

   );}; const   rootElement   =   document .getElementById( "root" ); ReactDOM.render( < Counter   /> ,   rootElement);

·  React Hooks 的規則

·  只能在 頂層 呼叫Hooks。不要在迴圈,條件或巢狀函式中呼叫Hook。

·  不要從常規JavaScript函式中呼叫Hook。只在React函式式元件呼叫Hooks。

 

·  自定義hooks可以選擇講解

·  react 內建hooks api

·  Basic Hooks

·  useState

·  useEffect

·  useContext

 

·  Additional Hooks

·  useReducer

·  useCallback

·  useMemo

·  useRef

·  useImperativeHandle

·  useLayoutEffect

·  useDebugValue

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913864/viewspace-2688738/,如需轉載,請註明出處,否則將追究法律責任。

相關文章