先圖,在上code
import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓" }; this.action = null; } render() { return ( <div> {this.state.name} <UseStateHook /> </div> ); } } const UseStateHook = () => { const [count, setCount] = useState(0); let tempCount = count; const delayShow = () => { setTimeout(() => { alert(tempCount); }, 5000); setCount(count + 5); }; return ( <div> 抓到老鼠的次數: {count} <button onClick={() => setCount(count + 1)}>+1</button> <button onClick={() => setCount(count - 1)}>-1</button> <br /> 閉包Bug測試: <button onClick={delayShow}>5秒後,顯示count且多抓5次老鼠</button> </div> ); }; ReactDOM.render(<App />, document.getElementById("app"));
明明就已經更新了,為何上面還是顯示0次了
這就是閉包BUG,他抓到的變數,還維持上一次的,沒進行最新的連結
此時就需要 用useRef 請參考這一篇:
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記