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

 <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('组件销毁')
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值