使用ref解决闭包问题
function Demo() {
const [count, setCount] = useState(0);
/**
*使用ref解决闭包问题
*/
const countRef = useRef(count);
countRef.current = count;
/** */
useEffect(() => {
const timer = setTimeout(() => {
console.log(countRef.current )
}, 3000);
return () => {
clearTimeout(timer);
}
}, [])
return (
<button
onClick={() => setCount(c => c + 1)}
>
click
</button>
)
}