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