react生命周期

constructor(){}  接受数据 声明数据和方法

render()渲染页面

componentDidMount() 页面结构加载完成  这里可以写数据请求

componentDidUpdate(){}  页面更新完成

componentwillUnmount(){}  组件离开

shouldComponentUpdate(nextProps,nextState){} 是否渲染到页面上去

页面打开会执行constructor(){} render(){} componentDidMount(){}这几个生命周期函数

执行了this.setState({}) 会执行render(){} componentDidUpdate(){}

执行了forceUpdate()强制更新也会触发render(){} componentDidUpdate(){}

React 组件的生命周期有三个不同的阶段:

  1. 初始渲染阶段:这是组件即将开始其生命之旅并进入 DOM 的阶段。
  2. 更新阶段:一旦组件被添加到 DOM,它只有在 prop 或状态发生变化时才可能更新和重新渲染。这些只发生在这个阶段。
  3. 卸载阶段:这是组件生命周期的最后阶段,组件被销毁并从 DOM 中删除。
import React, { Component } from 'react'

export default class Menu10 extends Component {

    constructor(props) {//接收数据 声明数据和方法
        super(props)
        console.log("1")
        this.state = {
            num: 10
        }
    }
    render() {   //渲染页面
        console.log(2)
        return (
            <div>
                {this.state.num}
                <button onClick={this.add}>+</button>
            </div >
        )
    }
    add = () => {
        this.setState({
            num: this.state.num + 1
        })
    }
    shouldComponentUpdate(nextProps, nextState) {
        // console.log(nextProps);
        console.log(nextState);
        if (nextState.num % 2 == 0) { //满足num是偶数才在页面上显示
            return true
        } else {
            return false;
        }
    }

    componentDidMount() {//这里写数据请求
        console.log(3)
        setTimeout(() => {
            // this.setState({
            //     num: 999
            // })
            this.state.num = 888;
            this.forceUpdate();  //强制更新会触发render()钩子函数 和componentDidUpdate()钩子函数
        }, 3000);
    }

    componentDidUpdate() {  //页面更新完成
        console.log(4)
    }

    componentWillUnmount() {//组件离开
        console.log("5")

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值