代码之家  ›  专栏  ›  技术社区  ›  FettFrank

测量渲染React组件的时间

  •  0
  • FettFrank  · 技术社区  · 2 年前

    在我的React应用程序中,我有一个组件,只有当用户悬停在另一个元素上时才会显示。我想用 useLayoutEffect 在这里,我返回一个清理,它测量清理函数调用和初始函数调用之间的时间差。我假设,由于cleanup函数是在初始 使用布局效果 函数,我计算的时间差总是正的,但事实似乎并非如此。有时该值为负值。我错过了什么?

    我的组件如下所示:

    const MyComponent = () => {
    
      useLayoutEffect(() => {
        const startTime = new Date();
        return () => {
           const endTime = new Date();
           const timeRendered = endTime.getMilliseconds() - startTime.getMilliseconds();
           console.log(timeRendered); // Expect this to be a positive number
        }
      }, []);
    
      return <>{/* stuff */}</>;
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   CertainPerformance    2 年前

    getMilliseconds 仅返回日期的毫秒部分,即0到999;这就像做 % 1000 在他们的时间戳上。试着减去日期,得到它们的时间戳差异。

    const MyComponent = () => {
    
      useLayoutEffect(() => {
        const startTime = new Date();
        return () => {
           const endTime = new Date();
           const timeRendered = endTime - startTime;
           console.log(timeRendered); // Expect this to be a positive number
        }
      }, []);
    
      return <>{/* stuff */}</>;
    }