React Hooks 獲取最新數據問題


如下情況: 獲取的是上次點擊時的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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM