【问题标题】:Assignments to the 'timeInterval' variable from inside React Hook useEffect will be lost after each render每次渲染后,从 React Hook useEffect 内部对 'timeInterval' 变量的分配将丢失
【发布时间】:2021-07-06 05:30:31
【问题描述】:

我需要每 6 秒自动重新渲染一次,我将组件定义如下。

const KioskPage = () => {

  const [time, setTime] = useState(Date.now())

  useEffect(() => {

    timeInterval = setInterval(() => setTime(Date.now()), 60000)

    return () => {
      clearInterval(timeInterval)
    }
  }, [])
}

但我收到了通知:

从 React Hook useEffect 内部对 'timeInterval' 变量的分配将在每次渲染后丢失。要随着时间的推移保留该值,请将其存储在 useRef Hook 中并将可变值保留在“.current”属性中。否则,你可以直接在 useEffect react-hooks/exhaustive-deps 中移动这个变量

为什么会这样?以及如何解决这个问题?

问候

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    从 React Hook useEffect 内部对 'timeInterval' 变量的分配将在每次渲染后丢失。

    举例说明:

    const KioskPage = () => {
    
      const [time, setTime] = useState(Date.now())
    
      let timeInterval;
      // ^^^^^ this piece of code gets run on each render, when state/prop changes.
      // this will, in practice, clear the `timeInterval` value set by your effect below, when the component re-renders after being mounted.
    
      useEffect(() => {
    
        timeInterval = setInterval(() => setTime(Date.now()), 60000)
        // ^^^^ this assignment gets run once when the component mounts
    
        return () => {
          clearInterval(timeInterval)
        }
      }, []);
      
      return (/* render something*/);
    }
    

    您可以按照建议通过“将此变量直接移动到 useEffect 中”来解决此问题。

    const KioskPage = () => {
      const [time, setTime] = useState(Date.now())
    
      useEffect(() => {
        const timeInterval = setInterval(() => setTime(Date.now()), 6000);
        // ^^^^^^^^^^^^^^^
    
        return () => {
          console.log('clearing!');
          clearInterval(timeInterval)
        }
      }, []);
    
      const formatted = new Date(time).toLocaleTimeString();
      return (
        <h1>Time: {formatted}</h1>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 2019-12-01
      • 2022-11-26
      • 2020-08-16
      • 2023-03-18
      • 1970-01-01
      • 2020-11-22
      • 2021-03-18
      相关资源
      最近更新 更多