API
约 99 字小于 1 分钟
2025-12-10
useEffect 清理函数
import { useState, useEffect } from 'react';
export function useCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
// return () => clearInterval(id);
}, []);
return count;
}问题
删除 return () => clearInterval(id) 清理函数后,页面上计数器每秒增加多少?
为什么会出现这个现象?
这在生产环境和开发环境会有不同表现吗?为什么?