1. 程式人生 > 其它 >react學習-生命週期鉤子函式

react學習-生命週期鉤子函式

react使用的越多,就會發現生命週期的參考價值越來越大

  1. componentWillMount: 當前元件的狀態和函式載入完畢,頁面還沒有開始渲染

  2. componentDidMount: 元件檢視渲染完畢

  3. shouldComponentUpdate: 狀態發生改變時觸發,檢視是否更新的狗子函式

    有返回值,返回值為true,就會更新檢視,執行鉤子函式4;返回值為false,就不會更新檢視,回到狀態2

  4. componentWillUpdate: 檢視即將更新

  5. componentDidUpdate: 檢視更新完成後執行的鉤子函式

  6. componentWillReceiveProps: 父元件傳進來的props值發生變化時觸發

  7. componentWillUnmount: 檢視即將銷燬時執行

    // 以下是生命週期元件

    import React from 'react'

    export default class LifeCycleDemo extends React.Component {

    constructor (props) {
    super(props)
    this.state = {
    data: '我是元件狀態',
    count: 0
    }
    }

    componentWillMount () {
    console.log('即將渲染檢視')
    }

    componentDidMount () {
    console.log('檢視渲染完畢')
    }

    shouldComponentUpdate () {
    console.log('狀態發生改變的時候觸發,決定檢視是否更新')
    // return true // 不更新
    return false // 更新
    }

    componentWillUpdate () {
    // 列印count改變之前的值
    console.log('檢視即將更新', this.state.count)
    }

    componentDidUpdate () {
    // 列印count改變之後的值
    console.log('檢視更新完成', this.state.count)
    }

    componentWillReceiveProps () {
    console.log('props發生變化時觸發')
    }

    componentWillUnmount () {
    console.log('檢視即將銷燬的時候觸發')
    }

    // 這裡要用箭頭函式,否則函式中的this指向為undefined
    changeState = ()=> {
    console.log(this)
    this.setState({
    count: this.state.count + 1
    })
    }

    render () {
    return (
    <div>我是元件
    <h3>{this.state.data}</h3>
    <span>{this.state.count}</span>
    <button onClick={this.changeState}>增加</button>
    </div>
    )
    }
    }

    注意:

    • 一般處理函式是直接放在類裡面

    • 鉤子函式中的this指向當前元件;但是自定義函式(changeState)中的this指向undefined,要想自定義函式中的this指向當前元件,必須用箭頭函式,或者用關鍵字bind改變函式中this的指向。