第八節(jié):React組件的生命周期

其實(shí)React組件并不是真正的DOM, 而是會(huì)生成JS對(duì)象的虛擬DOM, 虛擬DOM會(huì)經(jīng)歷創(chuàng)建,更新,刪除的過(guò)程

這一個(gè)完整的過(guò)程就構(gòu)成了組件的生命周期,React提供了鉤子函數(shù)讓我們可以在組件生命周期的不同階段添加操作


1. 生命周期函數(shù)的理解

1.1 組件生命周期函數(shù)說(shuō)明
  1. 組件生命周期函數(shù)主要分三類,組件的初始掛載,組件的更新渲染以及組件的卸載
  2. 有一些生命周期函數(shù)還在三個(gè)階段都會(huì)執(zhí)行的


1.2 組件的生命周期圖
生命周期流程圖.png


2. 生命周期函數(shù)

2.1 組件初始掛載
2.1.1 組件初始掛載生命周期函數(shù)認(rèn)識(shí)

當(dāng)組件實(shí)例被創(chuàng)建并插入 DOM 中時(shí)顽馋,其生命周期調(diào)用順序如下:

  1. constructor: 完成React數(shù)據(jù)的初始化
  2. conponentWillMount/UNSAFE_componentWillMonut: 頁(yè)面渲染前調(diào)用(未來(lái)將廢棄)
  3. render : class組件中唯一必須實(shí)現(xiàn)的方法,返回React元素渲染頁(yè)面
  4. componentDidMount 頁(yè)面初始化渲染完畢以后執(zhí)行


2.1.2 constructor函數(shù)

說(shuō)明:

  1. 如果不需要初始化state,或者不進(jìn)行方法的綁定,則不需要實(shí)現(xiàn)constructor構(gòu)造函數(shù)
  2. 在組件掛載前調(diào)用構(gòu)造函數(shù),如果繼承React.Component,則必須調(diào)用super(props)
  3. constructor通常用于處理了state初始化和為事件處理函數(shù)綁定this實(shí)例
  4. 盡量避免將props外部數(shù)據(jù)賦值給組件內(nèi)部state狀態(tài)

注意: constructor 構(gòu)造函數(shù)只在初始化化的時(shí)候執(zhí)行一次


示例代碼如下:

class MyCom extends React.Component{
    
    // 1. constructor 構(gòu)造函數(shù)
    constructor(props){
        super(props)
        console.log("組件初始化數(shù)據(jù)");
        // 初始化組件狀態(tài)
        this.state = {
            count: 0
        }
        // 處理事件函數(shù)綁定組件實(shí)例
        this.handleClick = this.handleClick.bind(this)    
    }

    
    handleClick(){
        this.setState(() => ({
            count: ++ this.state.count
        }))


    }
    
    render(){
        return (
            <div>
                <p>點(diǎn)擊次數(shù){ this.state.count }</p>
                <button onClick={ this.handleClick }>點(diǎn)擊</button>
            </div>
        )
    }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyCom/> ,document.getElementById("root"))


之前有講過(guò)組件state也可以不定義在constructor構(gòu)造函數(shù)中,事件函數(shù)也可以通過(guò)箭頭函數(shù)處理this問(wèn)題

因此如果不想使用constructor 也可以將兩者移出

示例代碼如下

class MyCom extends React.Component{
  
    // 初始化組件狀態(tài)
    state = {
        count: 0
    }

    // 箭頭函數(shù)處理this問(wèn)題
    handleClick= ()=>{
        this.setState(() => ({
            count: ++ this.state.count
        }))
    }
   //... 
}

結(jié)果一樣正常顯示


2.1.3 componentWillMount函數(shù)

說(shuō)明:

  1. componentWillMount生命周期函數(shù)在組件渲染前執(zhí)行,
  2. 使用時(shí)函數(shù)能正常運(yùn)行, 但是控制臺(tái)會(huì)打印警告,推薦使用UNSAFE_componentWillMount
  3. 但是react官網(wǎng)表示UNSAFE_componentWillMount即將過(guò)時(shí),不建議使用
  4. 這個(gè)生命周期函數(shù)也只會(huì)執(zhí)行一次

這個(gè)生命周期函數(shù)一般使用較少


示例代碼:

class MyCom extends React.Component{
    // 1. 初始化構(gòu)造函數(shù)
    constructor(props){
        super(props)
        console.log("組件初始化數(shù)據(jù)");
        // 初始化組件狀態(tài)
        this.state = {
            count: 0
        }
        // 處理事件函數(shù)綁定組件實(shí)例
        this.handleClick = this.handleClick.bind(this)    
    }

    // 2.組件渲染前執(zhí)行
    UNSAFE_componentWillMount(){
        console.log("組件內(nèi)容渲染前執(zhí)行 conponentWillMount");

    }

    handleClick(){
        this.setState(() => ({
            count: ++this.state.count
        }))


    }
    render(){
        return (
            <div>
                <p>點(diǎn)擊次數(shù){ this.state.count }</p>
                <button onClick={ this.handleClick }>點(diǎn)擊</button>
            </div>
        )
    }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyCom/> ,document.getElementById("root"))


2.1.4 render渲染函數(shù)

說(shuō)明:

  1. class組件中唯一必須實(shí)現(xiàn)的方法,其他生命周期函數(shù)沒(méi)有需求可以不寫(xiě),這個(gè)必須實(shí)現(xiàn)
  2. render函數(shù)返回一個(gè)通過(guò)JSX語(yǔ)法創(chuàng)建的React元素
  3. render函數(shù)應(yīng)為純函數(shù),意味著在不修改組件狀態(tài)和父組件傳遞的props時(shí),每次返回相同的結(jié)果
  4. render函數(shù)初始只會(huì)渲染一次,但是每次狀態(tài)的改變都會(huì)重新執(zhí)行


示例代碼:

class MyCom extends React.Component{
    // 1. 初始化構(gòu)造函數(shù)
    constructor(props){
        super(props)
        console.log("組件初始化數(shù)據(jù)");
        // 初始化組件狀態(tài)
        this.state = {
            count: 0
        }
        // 處理事件函數(shù)綁定組件實(shí)例
        this.handleClick = this.handleClick.bind(this)    
    }

    // 2.組件渲染前執(zhí)行
    UNSAFE_componentWillMount(){
        console.log("組件內(nèi)容渲染前執(zhí)行 conponentWillMount");

    }

    // 3. render渲染函數(shù)
    render(){
        console.log("render 渲染函數(shù)")
        return (
            <div>
                <p>點(diǎn)擊次數(shù){ this.state.count }</p>
                <button onClick={ this.handleClick }>點(diǎn)擊</button>
            </div>
        )
    }

    // 自定義事件函數(shù)
    handleClick(){
        this.setState(() => ({
            count: ++this.state.count
        }))


    }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyCom/> ,document.getElementById("root"))


2.1.5 componentDidMount函數(shù)

說(shuō)明:

  1. 組件渲染完畢以后執(zhí)行, 在render渲染函數(shù)之后
  2. componentDidMount生命周期函數(shù)只會(huì)執(zhí)行一次
  3. 可以在這個(gè)函數(shù)中發(fā)送ajax請(qǐng)求


示例代碼:

class MyCom extends React.Component{
    // 1. 初始化構(gòu)造函數(shù)
    constructor(props){
        super(props)
        console.log("組件初始化數(shù)據(jù)");
        // 初始化組件狀態(tài)
        this.state = {
            count: 0
        }
        // 處理事件函數(shù)綁定組件實(shí)例
        this.handleClick = this.handleClick.bind(this)    
    }

    // 2.組件渲染前執(zhí)行
    UNSAFE_componentWillMount(){
        console.log("組件內(nèi)容渲染前執(zhí)行 conponentWillMount");

    }

    // 3. render渲染函數(shù)
    render(){
        console.log("render 渲染函數(shù)")
        return (
            <div>
                <p>點(diǎn)擊次數(shù){ this.state.count }</p>
                <button onClick={ this.handleClick }>點(diǎn)擊</button>
            </div>
        )
    }

    // 4.組件渲染完畢后執(zhí)行 
    componentDidMount(){
        console.log("組件內(nèi)容渲染完畢,componentDidMount");

    }

    // 自定義事件函數(shù)
    handleClick(){
        this.setState(() => ({
            count: ++this.state.count
        }))


    }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyCom/> ,document.getElementById("root"))


2.2 組件渲染更新

組件的更新會(huì)出現(xiàn)兩種狀況, 父組件傳遞的props更新以及當(dāng)前組件更新自己的state

2.2.1 組件渲染更新生命周期函數(shù)認(rèn)識(shí)
  1. componentWillReceiveProps 組件接受的Props將要更新
  2. shouldComponentUpdate 是否允許組件渲染更新,函數(shù)返回true表示通過(guò), false表示不通過(guò),渲染不更新
  3. componentWillUpdate/UNSAFE_componentWillUpdate 組件內(nèi)容更新渲染前執(zhí)行
  4. render 組件內(nèi)容更新渲染
  5. componentDidUpdate 組件內(nèi)容更新渲染之后執(zhí)行


2.2.2 componentWillReceiveProps函數(shù)

說(shuō)明:

  1. 在父組件傳遞的props更新時(shí)執(zhí)行的生命周期函數(shù)
  2. 函數(shù)接受一個(gè)參數(shù)nextProps,為更新后的props數(shù)據(jù)
  3. 使用時(shí)控制臺(tái)會(huì)打印警告, 建議使用UNSAFE_componentWillReceiveProps
  4. 但是官網(wǎng)表示UNSAFE_componentWillReceiveProps也將會(huì)被廢棄



示例代碼如下:

// 子組件
class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  // 1. 組件將要接受props更新
  componentWillReceiveProps(){
    console.log("組件將要接受props更新: componentWillReceiveProps");
  }


  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }

  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))


  }
}


// 父組件
class MyParent extends React.Component{
  state = {
    num:0
  }

  changeNum = () => {
    this.setState(() => ({
      num: ++ this.state.num
    }) )
  }

  render(){
    return (
      <div>
        <button onClick={ this.changeNum }>父組件按鈕</button> 
        <MyCom num={this.state.num}/>
      </div>
    )
  }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyParent /> ,document.getElementById("root"))


2.2.3 shouldComponentUpdate函數(shù)

說(shuō)明:

  1. shouldComponentUpdate函數(shù)使用來(lái)判讀是否更新渲染組件
  2. 函數(shù)返回值是一個(gè)布爾值,為true,表示繼續(xù)走其他的生命周期函數(shù),更新渲染組件
  3. 如果返回一個(gè)false表示,不在繼續(xù)向下執(zhí)行其他的生命周期函數(shù),到此終止,不更新組件渲染
  4. 函數(shù)接受兩個(gè)參數(shù), 第一個(gè)參數(shù)為props將要更新的數(shù)據(jù), 第二個(gè)參數(shù)為state將要更新的數(shù)據(jù)


示例代碼如下:

// 子組件
class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  // 1. 組件將要接受props更新
  componentWillReceiveProps(nextProps){
    console.log("組件將要接受props更新: componentWillReceiveProps");
   
    
  }

  // 2. 是否允許組件渲染更新
  shouldComponentUpdate(nextProps, nextState){
    console.log("是否允許組件渲染更新: shouldComponentupdate");
    return true
  }

 
  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }
  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))


  }
}


// 父組件
//...


2.2.4 componentWillUpdate 函數(shù)

說(shuō)明:

  1. componentWillUpdate組件更新渲染前執(zhí)行
  2. 函數(shù)接受兩個(gè)參數(shù),第一個(gè)是props將要更新的數(shù)據(jù),第二個(gè)是state將要更新的數(shù)據(jù)
  3. 使用是瀏覽器會(huì)警告, 建議使用UNSAFE_componentWillUpdate
  4. 但是官網(wǎng)表示UNSAFE_componentWillUpdate也將被廢棄


示例代碼:

class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  // 1. 組件將要接受props更新
 componentWillReceiveProps(nextProps){
    console.log("組件將要接受props更新: componentWillReceiveProps");
   
    
  }

  // 2. 是否允許組件渲染更新
  shouldComponentUpdate(nextProps, nextState){
    console.log("是否允許組件渲染更新: shouldComponentupdate");
    return true
  }

  // 3.組件渲染更新前
  componentWillUpdate(nextProps, nextState){
    console.log("組件內(nèi)容更新前: componentWillUpdate");
   
  }

  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }


  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))


  }
}


// 父組件
//... 


2.2.5 render函數(shù)

更初始化一樣,沒(méi)事數(shù)據(jù)更新都會(huì)觸發(fā)render函數(shù)重新執(zhí)行, 更新頁(yè)面渲染


2.2.6 componentDidUpdate函數(shù)

說(shuō)明:

  1. 組件render執(zhí)行后,頁(yè)面渲染完畢了以后執(zhí)行的函數(shù)
  2. 接受兩個(gè)參數(shù),分別為更新前的props和state


示例代碼如下:

// 子組件
class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  // 1. 組件將要接受props更新
 componentWillReceiveProps(nextProps){
    console.log("組件將要接受props更新: componentWillReceiveProps");
   
    
  }

  // 2. 是否允許組件渲染更新
  shouldComponentUpdate(nextProps, nextState){
    console.log("是否允許組件渲染更新: shouldComponentupdate");
    return true
  }

  // 3.組件渲染更新前
  componentWillUpdate(){
    console.log("組件內(nèi)容更新前: componentWillUpdate");
   
  }

  // 4. render渲染函數(shù)
  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }

  // 5. 組件內(nèi)容更新渲染后
  componentDidUpdate( prevProps, prevState){
    console.log("組件內(nèi)容更新后執(zhí)行");
  }


  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))


  }
}


// 父組件
//...


2.3 組件銷毀

說(shuō)明:

  1. 組件銷毀階段只有一個(gè)生命周期函數(shù)componentWillUnmount
  2. componentWillUnmont組件銷毀前執(zhí)行的生命周期函數(shù),
  3. 沒(méi)有組件銷毀后執(zhí)行的生命周期函數(shù), 沒(méi)什么意義,組件被銷毀了,獲取不到對(duì)應(yīng)的內(nèi)容了
  4. 通過(guò)會(huì)在組件銷毀前清理一些不會(huì)被組件自動(dòng)清理的內(nèi)容, 如: 定時(shí)器,或一些特殊的事件綁定


示例代碼:

// 子組件
class MyCom extends React.Component{

    // 初始化組件狀態(tài)
    state = {
        count: 0
    }

    render(){
        console.log("render 渲染函數(shù)")
        return (
            <div>
                <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
                <p>子組件state數(shù)據(jù){ this.state.count }</p>
                <button onClick={ this.handleClick }>子組件按鈕</button>
            </div>
        )
    }

    componentWillUnmount(){
        console.log("組件被銷毀前執(zhí)行:componentWillUnmount")
    }


    // 自定義事件函數(shù)
    handleClick=()=>{
        this.setState(() => ({
            count: ++this.state.count
        }))

    }
}


// 父組件
class MyParent extends React.Component{
    state = {
        isShow: true
    }

    changeNum = () => {
        this.setState(() => ({
            isShow: !this.state.isShow
        }) )
    }

    render(){
        return (
            <div>
                <button onClick={ this.changeNum }>父組件按鈕</button> 
                { this.state.isShow ? <MyCom num={this.state.num}/>: "組件不顯示"}
            </div>
        )
    }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyParent /> ,document.getElementById("root"))


2.4 getSnapshotBeforeUpdate函數(shù)

說(shuō)明:

  1. getSnapshotBeforeUpdate必須跟componentDidUpdate一起使用,否則就報(bào)錯(cuò)
  2. 但是不能與componentWillReceivePropscomponentWillUpdate一起使用
  3. state和props更新都會(huì)觸發(fā)這個(gè)函數(shù)的執(zhí)行, 在render函數(shù)之后執(zhí)行
  4. 接受兩個(gè)參數(shù),更新前的props和當(dāng)前的state
  5. 函數(shù)必須return 返回結(jié)果
  6. getSnapshotBeforeUpdate返回的結(jié)果將作為參數(shù)傳遞給componentDidUpdate


示例代碼如下:

class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }

  getSnapshotBeforeUpdate(){
    console.log("getSnapshotBeforeUpdate")
    
    return true
  }

  componentDidUpdate(){
    console.log("組件內(nèi)容更新后執(zhí)行");
    
  }


  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))
  }
}


// 父組件
class MyParent extends React.Component{
  state = {
    isShow: true,
    num : 0
  }

  changeShow = () => {
    this.setState(() => ({
      isShow: !this.state.isShow
    }) )
  }

  changeNum = () => {
    this.setState(() => ({
      num: ++this.state.num
    }) )
  }

  render(){
    return (
      <div>
        <button onClick={ this.changeShow }>父組件按鈕</button> 
        <button onClick={ this.changeNum }>更新props</button> 
        { this.state.isShow ? <MyCom num={this.state.num}/>: "組件不顯示"}
      </div>
    )
  }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyParent /> ,document.getElementById("root"))


2.5 生命周期函數(shù)參數(shù)
生命周期函數(shù)參數(shù).png


2.6 特殊情況的生命周期函數(shù)

在React 17 版本之后將會(huì)改變幾個(gè)生命周期函數(shù)

更改的生命周期函數(shù).png


3. React 新增生命周期函數(shù)

3.1 新版生命周期圖

添加靜態(tài)方法后的生命周期函數(shù)圖

新的生命周期函數(shù)圖.png
不常用生命周期圖.png


3.2 新增的靜態(tài)方法

說(shuō)明:

  1. react新增了靜態(tài)方法getDerviedStateFromProps方法在生命周期中
  2. 這個(gè)方法用來(lái)替換componentWillReceiveProps,
  3. 通常會(huì)在ComponentWillReceiveProps中利用Props更新state
  4. getDerivedStateFromProps方法接受兩個(gè)參數(shù), 將要更新的props和state屬性
  5. 需要返回一個(gè)布爾值,不然會(huì)報(bào)錯(cuò)
  6. 還可以取代componentWillMount的功能, 因?yàn)檫@個(gè)靜態(tài)方法在組件初始化也會(huì)執(zhí)行


示例代碼:

class MyCom extends React.Component{
  
  // 初始化組件狀態(tài)
  state = {
    count: 0
  }

  // 生命周期上新增的靜態(tài)方法
  static getDerivedStateFromProps(nextProps,nextState){
    console.log("getDerivedStateFromProps");
      
      // 利用props的值更新當(dāng)前組件的狀態(tài)
    nextState.count = nextProps.num
    return true
  }


  render(){
    console.log("render 渲染函數(shù)")
    return (
      <div>
        <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
        <p>子組件state數(shù)據(jù){ this.state.count }</p>
        <button onClick={ this.handleClick }>子組件按鈕</button>
      </div>
    )
  }


  // 自定義事件函數(shù)
  handleClick=()=>{
      this.setState(() => ({
        count: ++this.state.count
      }))


  }
}


// 父組件
class MyParent extends React.Component{
  state = {
    isShow: true,
    num : 0
  }

  changeShow = () => {
    this.setState(() => ({
      isShow: !this.state.isShow
    }) )
  }

  changeNum = () => {
    this.setState(() => ({
      num: ++this.state.num
    }) )
  }

  render(){
    return (
      <div>
        <button onClick={ this.changeShow }>父組件按鈕</button> 
        <button onClick={ this.changeNum }>更新props</button> 
        { this.state.isShow ? <MyCom num={this.state.num}/>: "組件不顯示"}
      </div>
    )
  }
}


// 將組件渲染到頁(yè)面上
ReactDOM.render(<MyParent /> ,document.getElementById("root"))


4. 組件更新的方法

組件更新自己的狀態(tài),除了使用setState更新外,還可以通過(guò)forceUpdate更新

4.1 forceUpdate

說(shuō)明:

  1. 在組件中也可以組件實(shí)例調(diào)用forceUpdate方法直接更新數(shù)據(jù)
  2. forceUpdate方法會(huì)強(qiáng)制更新?tīng)顟B(tài),
  3. forceUpdate方法會(huì)執(zhí)行靜態(tài)方法getDerivedStateFromProps函數(shù)
  4. 但是forceUpdate方法不會(huì)觸發(fā)shouldComponetUpdate判斷是否更新的生命周期函數(shù)


示例代碼:

class MyCom extends React.Component{

    // 初始化組件狀態(tài)
    state = {
        count: 0
    }

    // 2. 是否允許組件渲染更新
    shouldComponentUpdate(nextProps, nextState){
        console.log("是否允許組件渲染更新: shouldComponentupdate");
        // nextState.count = nextProps.num
        return true
    }

    
    static getDerivedStateFromProps(nextProps,nextState){
        console.log("getDerivedStateFromProps");
        
        console.log(arguments);

        return true
    }


    // 自定義事件函數(shù)
    handleClick=()=>{
        this.state.count = ++ this.state.count

        this.forceUpdate();
    }

    // 4. render渲染函數(shù)
    render(){
        console.log("render 渲染函數(shù)")
        return (
            <div>
                <p>父組件傳遞props數(shù)據(jù){ this.props.num }</p>
                <p>子組件state數(shù)據(jù){ this.state.count }</p>
                <button onClick={ this.handleClick }>子組件按鈕</button>
            </div>
        )
    }
}


// 父組件
//...

示例說(shuō)明:

  1. 示例中直接修改狀態(tài)并不會(huì)觸發(fā)重新渲染
  2. 但是通過(guò)組件實(shí)例調(diào)用forceUpdate強(qiáng)制更新,會(huì)重新觸發(fā)頁(yè)面渲染
  3. 會(huì)觸發(fā)生命周期getDerivedStateFromProps函數(shù)執(zhí)行,
  4. 但是不會(huì)是否判斷是否更新的shouldComponentUpdate函數(shù)的執(zhí)行


5. 生命周期總結(jié)

5.1 常用生命周期函數(shù)

說(shuō)明:

  1. React生命周期函數(shù)很多, 但是并不是每一個(gè)都是那么的常用
  2. 因此可以將生命周期圖簡(jiǎn)化一下

常用生命周期圖

常用生命周期圖.png


5.2 生命周期總結(jié)
5.2.1 組件的三個(gè)生命周期分三個(gè)階段
  1. Mount : 初始化插入真實(shí)DOM
  2. Update : 數(shù)據(jù)更改重新渲染
  3. Unmount: 被移出真實(shí)的DOM


5.2.2 生命周期不同階段的鉤子函數(shù)
  • 第一次初始化渲染顯示: ReactDOM.render()

    • constructor(): 創(chuàng)建對(duì)象初始化state

    • componentWillMount() : 將要插入回調(diào)

    • render(): 用于插入虛擬DOM回調(diào)

    • componentDidMount() : 已經(jīng)插入回調(diào)(啟動(dòng)定時(shí)器,發(fā)送ajax,只執(zhí)行一次)

  • 每次更新 state: this.setState()

    • componentWillUpdate() : 將要更新回調(diào)

    • render() : 更新(重新渲染)

    • componentDidUpdate() : 已經(jīng)更新回調(diào)

  • 移除組件 : ReactDOM.unmountComponentAtNode(containerDom)
    • componentWillUnmount() : 組件將要被移出回調(diào)(收尾工作,例如清除定時(shí)器)


5.2.3 重要的鉤子函數(shù)
  • render(): 初始化渲染或更新渲染調(diào)用

  • componentDidMount() : 開(kāi)啟監(jiān)聽(tīng),發(fā)送ajax請(qǐng)求

  • componentWillUnmount(): 做一些收尾工作,如,清理定時(shí)器


5.3 示例代碼:

// 1. 定義組件
class Files extends React.Component {

    constructor (){
        super()

        // 定義狀態(tài)
        this.state = {
            opacity: 1
        }

    }
    removeComponent () {
        // 執(zhí)行unmountComponentAtNode()移出DOM節(jié)點(diǎn)
        ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }


    // 組件添加完后執(zhí)行的鉤子函數(shù)
    componentDidMount () {
        console.log('componentDidMount()')

        // 開(kāi)啟定時(shí)器
        this.timer = setInterval(function(){
            console.log('定時(shí)器...')

            // 1. 獲取狀態(tài)中的值
            let {opacity} = this.state;

            // 2. 改變透明度
            opacity -= 0.1;

            // 3. 判斷透明度,如果小于0,就變?yōu)?
            if(opacity <= 0){
                opacity = 1
            }

            // 4. 改變狀態(tài)
            this.setState({
                opacity
            })

        }.bind(this),200)
    }


    // 組件被移出后執(zhí)行的鉤子函數(shù)
    componentWillUnmount(){
        console.log('componentWillUnmount()')

        // 組件被移除后清除定時(shí)器
        clearInterval(this.timer)
    }

   
    render(){
        console.log('render()')
        // 取出狀態(tài)中的透明度
        let {opacity} = this.state;

        return (
            <div>
                <h2 style={{opacity:opacity}}>{this.props.msg}</h2>
                <button onClick={this.removeComponent}>刪除組件</button>
            </div> 
        )
    }
}

// 設(shè)置props類型
Files.propTypes = {
    msg: PropTypes.string
}


// 2. 渲染組件標(biāo)簽
ReactDOM.render(
    <Files msg="我太難了" />, 
    document.getElementById('root')
)


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市磅摹,隨后出現(xiàn)的幾起案子奴迅,更是在濱河造成了極大的恐慌渣淤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捻撑,死亡現(xiàn)場(chǎng)離奇詭異磨隘,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)顾患,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門番捂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人江解,你說(shuō)我怎么就攤上這事设预。” “怎么了犁河?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵鳖枕,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我桨螺,道長(zhǎng)宾符,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任灭翔,我火速辦了婚禮魏烫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘肝箱。我一直安慰自己哄褒,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布煌张。 她就那樣靜靜地躺著读处,像睡著了一般。 火紅的嫁衣襯著肌膚如雪唱矛。 梳的紋絲不亂的頭發(fā)上罚舱,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天井辜,我揣著相機(jī)與錄音,去河邊找鬼管闷。 笑死粥脚,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的包个。 我是一名探鬼主播刷允,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼碧囊!你這毒婦竟也來(lái)了树灶?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤糯而,失蹤者是張志新(化名)和其女友劉穎天通,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體熄驼,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡像寒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瓜贾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诺祸。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖祭芦,靈堂內(nèi)的尸體忽然破棺而出筷笨,到底是詐尸還是另有隱情,我是刑警寧澤龟劲,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布奥秆,位于F島的核電站,受9級(jí)特大地震影響咸灿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜侮叮,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一避矢、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧囊榜,春花似錦审胸、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至曙求,卻和暖如春碍庵,著一層夾襖步出監(jiān)牢的瞬間映企,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工静浴, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留堰氓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓苹享,卻偏偏與公主長(zhǎng)得像双絮,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子得问,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355