如果沒有用useRef,指向現在的位置,他會發生BUG 閉包bug,是非常常見的問題,因為每個 function每次執行,裡面的變數都是各自的記憶體位置,不會因為你新的function更 新了值,而幫你update它。
BUG詳細內容請參考這篇文章:
import React, { useState, useRef } 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); const tempCount = useRef(); tempCount.current = count; const delayShow = () => { setTimeout(() => { alert(tempCount.current); }, 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"));
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記