React 学习笔记 (六)(生命周期)

版权声明:未经允许,不可以转载哦~ https://blog.csdn.net/qq_39242027/article/details/83751361
 <Lifecycle></Lifecycle>

组件加载时触发的函数

constructor —> componentWillMount —> render —> componentDidMount

import React, { Component } from 'react';
class Lifecycle extends Component {
    constructor(props) {
        console.log('01构造函数')
        super(props);
        this.state = { 
            msg:'我是msg'
         };
    }
    // 数据将要挂载
    componentWillMount(){
        console.log('02组件将要挂载')
    }
    // 数据渲染
    render() {
        console.log('03数据渲染render')
        return (
            <div>
                <h2>生命周期 {this.state.msg}</h2>
            </div>
        );
    }
     // 数据挂载完成
    componentDidMount(){
        //dom操作放在这里 请求数据也放在这里
        console.log('04组件挂载完成')
    }
}
export default Lifecycle;

在这里插入图片描述

组件更新时触发的函数

shouldComponentUpdate —> componentWillUpdate —> render —> componentDidUpdate

import React, { Component } from 'react';
class Lifecycle extends Component {
    constructor(props) {
        console.log('01构造函数')
        super(props);
        this.state = { 
            msg:'我是msg'
         };
    }
 // 是否要更新数据 返回true会更新数据 返回false不会更新数据
//nextProps 父子组件传值时的数据 nextState改变后的数据
    shouldComponentUpdate(nextProps,nextState){
        console.log('01是否要更新数据')
        console.log(nextProps)
        console.log(nextState)
        return true
    }
// 数据将要更新
    componentWillUpdate(){
        console.log('02组件将要更新')
    }

    getMsg=()=>{
        this.setState({
            msg:'改变msg'
        })
    }
// 数据渲染
    render() {
        console.log('03数据渲染render')
        return (
            <div>
                <h2>生命周期 {this.state.msg}</h2>
                <button onClick={this.getMsg}>改变msg</button>
            </div>
        );
    }
 // 数据更新完成
    componentDidUpdate(){
        console.log('04组件数据更新')
    }
}

export default Lifecycle;

在这里插入图片描述

componentWillReceiveProps:在父组件里面改变props传值时触发

componentWillReceiveProps(){
    console.log('在父组件里面改变props传值时触发')
}

componentWillUnmount:组件销毁时触发的函数 销毁哪个写在哪个组件里

componentWillUnmount(){
    console.log('组件销毁')
}

猜你喜欢

转载自blog.csdn.net/qq_39242027/article/details/83751361