常见面试题目,实现自定义hooks
import { useEffect, useState } from 'react';
import styles from './index.module.css';
// 自定义hook
function useCountDown(initN: number) {
// 定义状态
const [n, setN] = useState(initN)
const changeCount = (n: number) => {
const timer = setTimeout(() => {
const current = --n; // n-- 值还是10未变 --n值为9改变
console.log('current', current)
setN(current)
}, 1000);
return timer;
}
// 监听状态变化
useEffect(() => {
const timer = changeCount(n);
console.log('timer :>> ', timer);
if (n === 0) {
setN(0);
clearTimeout(timer);
}
return () => {
clearTimeout(timer);
}
}, [n])
// 返回状态
return {n};
}
// 封装成组件
function Timer({ n }: { n: number }) {
const {n: time } = useCountDown(n)
return <span>{time === 0 ? '开始' : `剩余${time}秒`}</span>
}
export default function Count() {
return (
<div className={styles.container}>
<h2>倒计时</h2>
<Timer n={10} />
</div>
);
}