1. 程式人生 > 程式設計 >react新版本生命週期鉤子函式及用法詳解

react新版本生命週期鉤子函式及用法詳解

和舊的生命週期相比

在這裡插入圖片描述

準備廢棄三個鉤子,已經新增了兩個鉤子

React16 之後有三個生命週期被廢棄(但並沒有刪除)

  • componentWillMount( 元件將要掛載的鉤子)
  • componentWillReceiveProps(元件將要接收一個新的引數時的鉤子)
  • componentWillUpdate(元件將要更新的鉤子)

新版本的生命週期新增的鉤子

  • getDerivedStateFromProps
  • 通過引數可以獲取新的屬性和狀態
  • 該函式是靜態的
  • 該函式的返回值會覆蓋掉元件狀態

getSnapshot程式設計客棧BeforeUpdate

  1. 真實的DOM構建完成,但還未實際渲染到頁面中。
  2. 在該函式中,通常用於實現一些附加的dom操作
  3. 該函式的返回值,會作為componentDidUpdate的第三個引數

getDerivedStateFromProps

getDerivedStateFromProps不是給例項用的,需要將它定義為一個靜態方法。且需要給一個返回值


返回值可以使 state Obj 也可以是null
返回值是 state Obj 的話直接將之前的覆蓋 且無法改變
返回http://www.cppcns.comnull 對其他任何功能都沒有影響

// 從props哪裡得到一個派生的狀態
static getDerivedStateFromProps(props,state){
	return props
}

若 state的值 在人和時候都取決與 props 時,可以使用getDerivedStateFromProps

在這裡插入圖片描述

<div id="test"></div>
  <!-- 引入react核心庫 -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- 引入react-dom,用於支援react操作dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 引入babel 用於將jsx 轉換為 js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // 建立元件
  class Count extends React.Component{
    // 構造器
    constructor(props){
      console.log('Count---constructor')
      super(props)
      // 初始化狀態
      this.state = {count:0}
    }

    // 掛載完成的鉤子
    componentDidMount(){
      console.log('Count---componentDidMount')
    }

    // 解除安裝元件按鈕的回撥
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // 實現 +1
     add =()=>{
      // 獲取原狀態
      const {count} = this.state
      // 更新狀態
      this.setState({count:count+1})
    }

    // 強制更新按鈕的回撥
    force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state){
      console.log('getDerivedStateFromProps',props,state)
      return props
    }

    // 控制組件更新的閥http://www.cppcns.com
門 shouldComponentUpdate(){ console.log('Count---shouldComponentUpdate') // 如果返回值為false閥門關閉 預設為true return true } // 元件更新完畢的鉤子 componentDidUpdate(){ console.log('Count---componentDidUpdate') } // 元件將要解除安裝的鉤子 componentWillUnmount(){ console.log('Count---componentWillUnmount'); } render(){ console.log('Count---render') const {count} = this.state return( <div> <h2>當前求和為:{count}</h2> <button onClick={this.add}>點我+1</button> <button onClick={this.death}>點我解除安裝元件</button> <button onClick={this.force}>點我強制更新(不改變資料)</button> </div> ) } } // 渲染元件 ReactDOM.render(<Count count={166}/>,document.getElementById('test')) </script>

執行結果

在這裡插入圖片描述

getSnapshotBeforeUpdate

返回值可以是null 或者 一個快照
如果是null 則沒有任何影響
如果是一個快照則可以將返回值傳遞給componentDidUpdate 的第三個引數
componentDidUpdate 能接收的三個引數
分別是
先前的props、先前的state和getSnapshotBeforeUpdate返回的快照
prevprops、 prevstate、snapshotValue

在這裡插入圖片描述

<div id="test"></div>
  <!-- 引入react核心庫 -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- 引入react-dom,用於支援react操作dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 引入babel 用於將jsx 轉換為 js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // 建立元件
  class Count extends React.Component{
    // 構造器
    constructor(props){
      console.log('Count---constructor')
      super(props)
      // 初始化狀態
      this.state = {count:0}
    }

    // 掛載完成的鉤子
    componentDhttp://www.cppcns.comidMount(){
      console.log('Count---componentDidMount')
    }

    // 解除安裝元件按鈕的回撥
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // 實現 +1
     add =()=>{
      // 獲取原狀態
      const {count} = this.state
      // 更新狀態
      this.setState({count:count+1})
    }

    // 強制更新按鈕的回撥
    force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state)
      return null
    }

    getSnapshotBeforeUpdate(){
      console.log('getSnapshotBeforeUpdate');
      return "eee"
    }

    // 控制組件更新的閥門
    shouldComponentUpdate(){
      console.log('Count---shouldComponentUpdate')
      // 如果返回值為false閥門關閉  預設為true
      return true
    }

    // 元件更新完畢的鉤子
    componentDidUpdate(preProps,preState,snapshotValue){
      console.log('Count---1componentDidUpdate',preProps,snapshotValue);
    }

     // 元件將要解除安裝的鉤子
     componentWillUnmount(){
      console.log('Count---componentWillUnmount');
    }

    render(){
      console.log('Count---render')
      const {count} = this.state
      return(
        <div>
          <h2>當前求和為:{count}</h2>
          <button onClick={this.add}>點我+1</button>  
          <button onClick={this.death}>點我解除安裝元件</button>  
          <button onClick={this.force}>點我強制更新(不改變資料)</button>  
        </div>
      )
    }
  }
  
  // 渲染元件
    ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

總結

生命週期的三個階段(新)

一、 初始化階段: 由ReactDOM.render()觸發—初次渲染

constructor()getDerivedStateFromPropsrender()componentDidMount()

二、 更新階段: 由元件內部this.setSate()或父元件重新render觸發

getDerivedStateFromPropsshouldComponentUpdate()render()getSnapshotBeforeUpdatecomponentDidUpdate()

三、解除安裝元件: 由ReactDOM.unmountComponentAtNode()觸發

componentWillUnmount()

重要的勾子

render:初始化渲染或更新渲染呼叫componentDidMount:開啟監聽,傳送aj程式設計客棧ax請求componentWillUnmount:做一些收尾工作,如: 清理定時器

即將廢棄的勾子

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

現在使用會出現警告,下一個大版本需要加上UNSAFE_字首才能使用,以後可能會被徹底廢棄,不建議使用。

到此這篇關於react新版本生命週期鉤子函式的文章就介紹到這了,更多相關react 生命週期 鉤子函式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!