React 常见的生命周期

本文详细介绍了React组件的三个关键生命周期阶段:装载阶段的`componentDidMount`,用于初始化数据;更新阶段的`shouldComponentUpdate`与`componentDidUpdate`,优化性能;销毁阶段的`componentWillUnmount`,释放资源。通过实例演示了如何在每个阶段进行操作和优化视图更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import React from 'react'

// 三个阶段:装载阶段(3)、更新阶段(2)、销毁阶段(1)
export default class LifeDemo extends React.Component {
    // 装载阶段(3)
    // 执行顺序:constructor / render / componentDidMount

    // 构造器
    // super 必须是第一行代码,声明式变量定义在 this.state 中
    // 在构造器中,props 和 state 不要交叉,他俩没有任何关系
    // 在构造器中,不要执行 this.setState()
    // 在构造器中,不要开启异步任务,比如调接口、定时器等
    constructor(props) {
        super(props)
        this.state = {
            count: 1,
            flag: false
        }
    }

    // 相当于 Vue 中的 mounted()
    // 表示 DOM 初始化已经完成,所有虚拟 DOM 都已经被渲染成真实 DOM 了
    // 一般在这里,可以调接口、定时器、DOM 操作
    componentDidMount() {
        console.log('------------componentDidMount')
    }

    // 更新阶段(2)
    // 执行顺序:shouldComponentUpdate / componentDidUpdate
    // 这是一个开关:用于控制是否更新
    // 这个生命周期,用于性能优化,可以精确控制某些state变量发生变化时不更新视图
    // 实际工作中很少用,我们会用函数式组件(PureComponent)作为替代解决
    shouldComponentUpdate(nextProps, nextState) {
        console.log('------------shouldComponentUpdate')
        console.log('开关打开state', nextState)
        let { flag } = this.state
        return (nextState.flag === flag && nextState.count <= 10)
    }

    // 相当于 Vue 中的 update
    // 表示 DOM 已经更新完成
    // 在该生命周期中,同样不要使用 this.setState()
    componentDidUpdate() {
        console.log('------------componentDidUpdate')
    }

    // 销毁阶段(1)
    // 相当于Vue中的beforeDistroy
    // 关闭长连接、定时器,清缓存
    componentWillUnmount() {
        console.log('------------componentWillUnmount')
    }

    // render() 非常特殊
    // 它是React类组件中唯一的一个必须的生命周期
    // 它在装载阶段和更新阶段都会运行
    // 当 state 发生变化时,render 执行二次渲染,是根据 diff 运算的脏节点来更新界面,不是全部更新
    // 在render的return之前可以进行业务逻辑操作
    // 在render中或者自定义的渲染函数中,不能使用 this.setState()
    render() {
        let { count, flag } = this.state
        console.log('------------render')
        return (
            <div>
                <h1>测试生命周期</h1>
                <hr />
                <h2>{count}</h2>
                <button onClick={() => this.setState(state => ({ count: state.count + 1 }))}>改变count(当count大于10时,不更新)</button>
                <button onClick={() => this.setState(state => ({ flag: !state.flag }))}>改变flag(永远不触发视图更新)</button>
            </div>
        )
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值