feat(chapter3): add effect hook demo

Demonstrate resize subscriptions with cleanup and show an async effect that updates the Ant Design button state.
This commit is contained in:
jiawei
2026-08-30 17:09:32 +08:00
parent 7e0e3527e9
commit 4823d13938
2 changed files with 68 additions and 0 deletions
@@ -0,0 +1,60 @@
// src/app/demo/_components/effect.tsx
// ...
'use client';
import { Button } from 'antd';
import { type FC, useEffect, useState } from 'react';
import $styles from './style.module.css';
const EffectDemo: FC = () => {
const [ghost, setGhost] = useState<boolean>(false);
const [width, setWidth] = useState(0);
const [red, setRed] = useState<boolean>(false);
const toggleGhostBtn = () => setGhost(!ghost);
useEffect(() => {
const resizeHandle = () => {
setWidth(window.innerWidth);
console.log('浏览器宽度改变');
};
const frameId = requestAnimationFrame(resizeHandle);
window.addEventListener('resize', resizeHandle);
return () => {
cancelAnimationFrame(frameId);
window.removeEventListener('resize', resizeHandle);
};
}, []);
useEffect(() => {
(
async () => {
await new Promise((resolve) => {
setTimeout(() => {
resolve('done');
}, 1000);
});
setRed(ghost);
}
)();
}, [ghost]);
useEffect(() => {
console.log('只在第一次或重新渲染时触发');
}, []);
return (
<div className={$styles.container}>
<h2 className="text-center">useEffect Demo</h2>
<p className="py-5 text-center">{ghost ? 'ghost' : '普通'}</p>
<div className="flex flex-col justify-center">
<Button type="primary" onClick={toggleGhostBtn} ghost={ghost} danger={red}>
</Button>
<p className="pt-5 text-center">: {width}</p>
</div>
</div>
);
};
export default EffectDemo;
+8
View File
@@ -3,6 +3,8 @@
import { FC } from 'react'; import { FC } from 'react';
import { Button } from 'antd'; import { Button } from 'antd';
import StateDemo from './_components/state'; import StateDemo from './_components/state';
import EffectDemo from './_components/effect';
import RefDemo from './_components/ref';
import $styles from './page.module.css'; import $styles from './page.module.css';
@@ -19,6 +21,12 @@ const DemoPage: FC = () => (
<div className={$styles.demo}> <div className={$styles.demo}>
<StateDemo /> <StateDemo />
</div> </div>
<div className={$styles.demo}>
<EffectDemo />
</div>
<div className={$styles.demo}>
<RefDemo />
</div>
</div> </div>
</div> </div>
</div> </div>