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>
  • 相关阅读:
    是否是轮回(续)
    夜雨做成秋
    53分
    浮生六记 一成长星和月
    企业信息化常见缩略语汇总
    是否是轮回
    对信号集操作函数的使用方法和顺序
    fcntl.h
    关于linux信号量的基本使用
    linux 共享内存
  • 原文地址:https://www.cnblogs.com/it-Ren/p/14917368.html
Copyright © 2011-2022 走看看