简体   繁体   English

如何在超时 function 内获取更新的 useState() 值?

[英]How to get updated useState() value inside timeout function?

I'm currently trying to get the latest updates into a timeout function.我目前正在尝试将最新更新放入超时 function。 This means I want to have c updated to 1 without having to use something like the useRef hook.这意味着我想将c更新为1而不必使用类似useRef挂钩的东西。

const [c, s] = useState<number>(0)

    const f = () => {
        s(1)
        setTimeout(() => console.log(c), 600)
    }

    return (
        <div
            style={{ width: '100%', height: '100%', backgroundColor: 'black' }}
            onMouseEnter={f}
        >
            test
        </div>
    )

Without a reference, you can try useEffect hook:没有参考,你可以试试useEffect钩子:

const [c, setC] = useState<number>(0);

useEffect(() => {
  setTimeout(() => {
    console.log(c);
  }, 600);
}, [c]);

const f = () => {
  setC(1);
};

return <div onMouseEnter={f}>test</div>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 highcharts 中的 setInterval function 获取 react useState 挂钩的更新值? - how to get updated value of react useState hook from setInterval function in highcharts? 如何使用更新后的 useState 值? - How to use the updated useState value? 如何在 useEffect 中使用 useState,访问组件挂载时更新的 useState 值? - How to use useState inside useEffect, accessing the updated useState value on component mount? 为什么 useState 有这种行为,以及如何在我设置值的同一函数中获取更新值? 在反应原生 - why useState have this behavier and how I can get updated value in in same function where I set value? In react-native 无法获取更新的 state 值 useState 和 UseEffect - Cannot get the updated the state value useState and UseEffect 无法在 function 中获取 Usestate 的值 - Impossible to get the value of an Usestate in a function 为什么 useState 值没有在 useHotkeys 回调中更新? - Why does a useState value isn't updated inside useHotkeys callback? 如何获取 function 中传递给另一个组件的 useState 变量的值 - How to get value of useState variable in function that passed to another component 如何在一个 function 中使用两个 useState 以便第二个 useState 可以使用第一个更新的 useState? - how to use two useState in one function so that the second useState can use the first updated useState? 如何在 function 中处理时获取更新值 - How to get updated value while processing in a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM