【问题标题】:useEffect() vs setTimeout() for side effects [duplicate]useEffect() vs setTimeout() 的副作用[重复]
【发布时间】:2021-01-25 17:05:34
【问题描述】:

我有一个关于 useEffect()setTimeout() 的一般性问题。

import { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => console.log(count)); // effect

  const handleClick = () => {
    setCount(count + 1);
    setTimeout(() => console.log(count), 5000); // log to console after 5 seconds
  }

  return (
    <>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click Me</button>
    </>
  );
}

export default Counter;

在上面的代码中,

setCount(count + 1);
setTimeout(() => console.log(count), 5000);

使用setTimeout(),我试图在5 秒后记录count,到那时setCount(),虽然是异步的,但肯定会完成。

那为什么仍然打印 count 的先前值,而 useEffect() 代码打印更新后的值?谁能告诉我我错过了什么。

【问题讨论】:

    标签: reactjs react-hooks use-effect


    【解决方案1】:

    关于这段代码有很多话要说:

    import { useState, useEffect } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      useEffect(() => console.log(count), [count]); // Add the dependencies array, the callback of use effect will be call only if a dependency is updated
    
      const handleClick = () => {
        setCount((count) => count + 1); // Use a callback which takes as argument the previous state, because if you click multiple times on the button, as setCount is asynchronous, it won't add 1 for each click
        setTimeout(() => console.log(count), 5000); // log to console after 5 seconds
      }
    
      return (
        <>
          <p>You clicked {count} times</p>
          <button onClick={handleClick}>Click Me</button>
        </>
      );
    }
    
    export default Counter;
    

    我认为这是因为 setTimeout 的回调是在计算 njew count 变量之前评估的,所以它记录了以前的值,其中 useEffect 的回调是在更新依赖项时调用的,所以当你增加 count 时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多