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>
原文地址:https://www.cnblogs.com/it-Ren/p/14917368.html