今天碰到一道面试题目,题目是关于React中useRef的使用,代码如下:
const App = ()=>{
const [count, setCount] = useState(0);
const lastCount = useRef(count);
useEffect(()=>{
lastCount.current = count;
})
function handleAlertClick(){
setTimeout(()=>{
alert(lastCount.current)
},3000);
}
return <div>
<p>你点击了{count}次</p>
<button onClick={()=>setCount(count+1)}>click me</button>
<button onClick={handleAlertClick}> show Alert</button>
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
问题是:多次点击第一个按钮,中途点击一下第二个按钮,然后再点击第一个按钮,弹窗弹出的数字是什么样的,解释一下流程。
每次弹出来都是最新的值,流程就是setCount之后触发rerender,然后count变更了,useEffect由于没有指定依赖所以每次rerender都会重新执行,故而每次ref都是最新值,如果useEffect依赖为空数组则每次都是0