zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    线程同步(二)—— 条件变量
    线程同步(一)—— 互斥锁
    进程同步(四)—— 消息队列
    Nginx反向代理服务器的配置
    散列表(hash表)
    浅谈bitmap
    进程空间分配和堆栈大小
    拓扑排序
    归并排序
    快速排序
  • 原文地址:https://www.cnblogs.com/it-Ren/p/14917368.html
Copyright © 2011-2022 走看看