react hooks 中的“闭包陷阱”
问题描述
开发当中遇到了一个问题,当在 useEffect 中使用 setInterval 定时器时,定时器的函数参数中使用到的 state 无法获取到最新的状态。看代码:
function ADD(){
const [count, setCount] = useState(1);
const fn = () => {
setInterval(() => {
console.log(count);
}, 1000);
};
useEffect(fn, []);
const addCount = () => {
setCount(pre => ++pre);
};
return