React生命周期函數


/*
https://reactjs.org/docs/react-component.html


React生命周期函數:

    組件加載之前,組件加載完成,以及組件更新數據,組件銷毀。

    觸發的一系列的方法 ,這就是組件的生命周期函數


組件加載的時候觸發的函數: 

    constructor 、componentWillMount、 render 、componentDidMount

組件數據更新的時候觸發的生命周期函數:

    shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate


你在父組件里面改變props傳值的時候觸發的:

    componentWillReceiveProps


組件銷毀的時候觸發的:

    componentWillUnmount


必須記住的生命周期函數:


    *加載的時候:componentWillMount、 render 、componentDidMount(dom操作)

    更新的時候:componentWillUpdate、render、componentDidUpdate

    *銷毀的時候: componentWillUnmount




*/


import React, { Component } from 'react';

class Lifecycle extends Component {
    constructor(props) {

        console.log('01構造函數');
        super(props);
        this.state = { 

            msg:'我是一個msg'
         };
    }  

    //組件將要掛載的時候觸發的生命周期函數
    componentWillMount(){

        console.log('02組件將要掛載');
    }
    //組件掛載完成的時候觸發的生命周期函數
    componentDidMount(){

        //dom操作放在這個里面    請求數據也放在這個里面

        console.log('04組件將要掛載');
    }


    //是否要更新數據  如果返回true才會執行更新數據的操作
    shouldComponentUpdate(nextProps, nextState){
        console.log('01是否要更新數據');

        console.log(nextProps);

        console.log(nextState);

        return true;
    }

    //將要更新數據的時候觸發

    componentWillUpdate(){
        console.log('02組件將要更新');
    }
    //組件更新完成
    componentDidUpdate(){
        console.log('04組件數據更新完成');
    }

    // 你在父組件里面改變props傳值的時候觸發的

    componentWillReceiveProps(){

        console.log('父子組件傳值,父組件里面改變了props的值觸發的方法')
    }

    setMsg=()=>{

        this.setState({

            msg:'我是改變后的msg的數據'
        })
    }

    //組件銷毀的時候觸發的生命周期函數   用在組件銷毀的時候執行操作
    componentWillUnmount(){

            console.log('組件銷毀了');
    }
    render() {
        console.log('03數據渲染render');
       
        return (
            <div>

                生命周期函數演示--- {this.state.msg}-----{this.props.title}

                <br />
                <br />

                <button onClick={this.setMsg}>更新msg的數據</button>
            </div>
        );
    }
}

export default Lifecycle;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM