React - useEffect的使用

import React, { Component, useState, useEffect } from 'react'
import { useControl } from './hooks/useControl'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'
import {
// 🤴🏻🟨 推荐使用as将路由重命名为Router
HashRouter,
BrowserRouter as Router,
Route,
Link,
NavLink,
Switch,
Redirect,
} from 'react-router-dom'
import { getChannelsAPI } from './api/channel'
const root = ReactDOM.createRoot(document.getElementById('root'))
// useEffect的基本使用
// useEffect(() => {每次状态变化,会自动执行,可以获取更新后的状态})
function AppCom01() {
const [count, setCount] = useState(0)
useEffect(() => {
// 每次count变化,回调函数会自动执行,可以获取到更新之后的count
console.log('count发生了变化 ~~~ ', count)
document.title = count
})
return (
<>
<div>
<h1>count: {count}</h1>
<button
onClick={() => {
setCount(count + 1)
}}
>
plus(1)
</button>
</div>
</>
)
}
// 学习目标: useEffect模拟生命周期 - 更新时
// 1. useEffect(() => {}, []) => 挂在之后
// 2. useEffect(() => {}, [依赖项]) => 挂载更新二合一
function AppCom02() {
const [count, setCount] = useState(0)
// 挂载后
// useEffect(() => {
// console.log('执行=>')
// document.title = count
// }, [])
// 模拟更新之后
// 👹 代表:挂载\更新二合一 等同于 componentDidUpdate和componentDidMount
// 类似vue中的watch 开启immediately
useEffect(() => {
console.log('执行了 ====> ', count)
document.title = count
}, [count])
return (
<>
<div>
<h1>count: {count}</h1>
<button
onClick={() => {
setCount(count + 1)
}}
>
plus(+1)
</button>
</div>
</>
)
}
// 🍅 useEffect模拟生命周期 - 第二个参数小结
// 语法:
// 1. useEffect(() => {}, []) 挂载之后
// 2. useEffect(() => {}, [依赖项]) 挂载更新二合一
// 3. useEffect(() => {}) 👎 会监听所有状态的变化
function AppCom03() {
const [count, setCount] = useState(0)
const [msg, setMsg] = useState('We are the world!')
// 👳🏻‍♂️ 挂载之后
useEffect(() => {
console.log('挂载之后,只会执行一次🥩')
}, [])
// 👳🏻‍♂️ 代表: 挂载更新二合一
// 依赖项:只监听依赖项的变化
useEffect(() => {
console.log('count: ', count)
}, [count])
// 代表:挂载更新二合一
// 不写依赖项:监听所有的数据变化
// 👎👎
useEffect(() => {
console.log('I can listen all data change and execute some logic')
})
return (
<>
<div>
<h1>count: {count}</h1>
<h1>msg: {msg}</h1>
<button onClick={() => setCount(count + 1)}>plus(+1)</button>
<br />
<button onClick={() => setMsg(msg + '~')}>click(+~)</button>
</div>
</>
)
}
// 🍅 useEffect监听多个状态的变化
function AppCom04() {
const [count, setCount] = useState(0)
const [msg, setMsg] = useState('we are the world')
// 1. 🍑分开监听
useEffect(() => {
console.log('I can listen count.', count)
}, [count])
useEffect(() => {
console.log('I can listen msg', msg)
}, [msg])
// 2. 🍓同时监听
useEffect(() => {
console.log('I can listen count and msg', count + msg)
}, [count, msg])
return (
<>
<div>
<code>
count: {count}
msg: {msg}
</code>
<button onClick={() => setCount(count + 1)}>click - plus(+1)</button>
<button onClick={() => setMsg(msg + '~')}>click - plus(+~)</button>
</div>
</>
)
}
// 🍅 useEffect模拟卸载时生命周期 - 卸载时
function AppCom05() {
const [isShow, setIsShow] = useState(true)
return (
<div>
{isShow && <Child />}
<button onClick={() => setIsShow(!isShow)}>点击卸载子组件</button>
</div>
)
}
function Child() {
// 在子组件中挂载时监听窗口改变事件
const resizeFn = () => {
console.log('窗口发生改变...')
}
useEffect(() => {
window.addEventListener('resize', resizeFn)
// 卸载的时候: useEffect(() => {return 卸载时会自动执行的回调函数})
return () => {
window.removeEventListener('resize', resizeFn)
}
}, [])
return (
<>
<div>我是子组件!!!</div>
</>
)
}
// 🍅 useEffect综合写法
function AppCom06() {
const [isShow, setIsShow] = useState(true)
return (
<>
<div>
{isShow && <ChildCom06 />}
<br />
<button onClick={() => setIsShow(!isShow)}>点击卸载子组件</button>
</div>
</>
)
}
function ChildCom06() {
const resizeFn = () => {
console.log('window change ..')
}
// 🍓 一个useEffect只维护一个逻辑的挂载和卸载
// 🍓 多个逻辑,使用多个useEffect维护
useEffect(() => {
window.addEventListener('resize', resizeFn)
return () => {
window.removeEventListener('resize', resizeFn)
}
}, [])
}
// 🍑 useEffect发送请求获取数据
function AppCom07() {
const [list, setList] = useState([])
const loadData = async () => {
const res = await getChannelsAPI()
setList(res.data.channels)
}
// 🟨 useEffect接收同步的回调函数,不能是异步函数
useEffect(() => {
loadData()
}, [])
return (
<>
<div>
APP
{list.map((item) => {
return (
<>
<div key={item.id}>{item.name}</div>
</>
)
})}
</div>
</>
)
}
const divNode = (
<div>
<AppCom07 />
</div>
)
root.render(divNode)
posted @   Felix_Openmind  阅读(94)  评论(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;}
点击右上角即可分享
微信分享提示