React-生命周期

import React, { Component } from 'react'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'
const root = ReactDOM.createRoot(document.getElementById('root'))
// React
// 1. constructor - 构造函数
// 2. render - 渲染函数
// 3. componentDidMount 【生命周期 - 挂载阶段】
// 4. componentDidUpdate 【生命周期 - 更新阶段】
// 5. componentWillUnmount 【生命周期 - 卸载阶段】
// 触发更新的两种方式
// 1. setState
// 2. props改变
// 注意: 更新阶段的钩子函数中,不能执行setState,否则进入死循环
class MyApp01 extends React.Component {
// 对标 vue中的created,表示创建
// 🪔场景: 1. 初始化state 2. 创建ref
// 👎 不会在constructor中发起请求获取数据
constructor(props) {
// 语法规则: super()表示集成父级所有的属性和方法,不能省略
super(props)
// 👎 一般不在constructor中声明状态
}
// 👍
state = {
count: 404,
}
// 💥 表示渲染JSX,必须写的一个钩子函数
// 作用: 表示重新渲染
render() {
console.log('【MyApp01】render ----> ')
const { count } = this.state
return (
<>
<div>
<h1>{count}</h1>
<div>
<ChildCom count={count}></ChildCom>
<button
onClick={() => {
this.setState({
count: count + 1,
})
}}
>
点我更新count
</button>
</div>
</div>
</>
)
}
// 对标:vue中的mounted
componentDidMount() {
console.log('【MyApp01】挂在完毕~~')
}
}
class ChildCom extends React.Component {
render() {
console.log('【ChildCom】render -----------> ')
return (
<>
<div>[ChildCom display count]{this.props.count}</div>
</>
)
}
// 作用:表示更新之后,类似于Vue中的updated
// 场景:做缓存
componentDidUpdate() {
console.log('【ChildCom】componentDidUpdate -----------> ')
}
}
class MyApp02 extends React.Component {
state = {
isShow: true,
}
render() {
const { isShow } = this.state
return (
<>
<div>{isShow && <ChildForApp02Com />}</div>
</>
)
}
}
class ChildForApp02Com extends React.Component {
handleResize = () => {
console.log('窗口发生改变了 ==========> ')
}
componentDidMount() {
window.addEventListener('resize', this.handleResize)
}
componentWillUnmount() {
console.log('ChildForApp02Com is unloading ...')
window.removeEventListener('resize', this.handleResize)
}
render() {
return (
<>
<div>ChildForApp02Com</div>
</>
)
}
}
const divNode = (
<div>
<MyApp02 />
</div>
)
root.render(divNode)
// 生命周期总结
// 生命周期: 【挂载阶段】 =》 【更新阶段】 =》 【卸载阶段】
// 1. constructor:
// 作用:初始化state和ref 👎几乎不用
// 类似:Vue中的created
// 2. render: 渲染DOM
// 3. componentDidMount
// 作用:表示挂载完成
// 类似:Vue中的mounted
// 使用场景: 【发送请求】【最先获取DOM元素】【监听事件/定时器】
// 4. componnetDidUpdate
// 作用:表示数据更新之后
// 类似:Vue中的updated
// 使用场景:【1.缓存处理】【2.获取更新的数据】
// 触发更新阶段的方式
// 1. setState
// 2. 💥props值的改变
// 5. componentWillUnmount
// 作用:卸载之前
// 类似于:Vue中beforeDestory
// 场景:做清除的动作, eg:销毁定时器/解绑事件
posted @   Felix_Openmind  阅读(11)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示