如下情況: 獲取的是上次點擊時的count值
const [count, setCount] = React.useState(0); function alertCount() { setTimeout(() => { alert(count) // 點擊5次 后再觸發,顯示的是0 }, 1000) } <div>count: {count}</div> <button onClick={() => setCount(count + 1)}>+</button> <button onClick={alertCount}>alert count</button>
使用useRef(每次引用同一個地址), 可以獲取最新值, 而createRef 是使用新的地址, 所以也和count一樣, 是上次的數值
const [count, setCount] = React.useState(0); const refUseRef = React.useRef(count); useEffect(() => { refUseRef.current = count; }) function alertCount() { setTimeout(() => { alert(refUseRef.current) // 點擊5次 后再觸發,顯示的是5 }, 1000) } <div>count: {count}</div> <div>refUseRef.current: {refUseRef.current}</div> <button onClick={() => setCount(count + 1)}>+</button> <button onClick={alertCount}>alert count</button>