我如何计算我的组件在反应组件中渲染了多少次

问题描述 投票:0回答:4

我有以下 React 组件,

import React, {useState} from "react"

export default function App(){
  const [state, setState] = useState(0);
  return <>
    <button onClick={() => setState(state + 3)}>Click to increment</button>
    {state}
  </>
}

如何能够显示我的组件渲染的次数! 谢谢!

javascript reactjs
4个回答
6
投票

renderCount.current
表示组件的渲染计数。您可以使用以下代码,但对于react 18,第一次renderCount.current将等于2,然后将增加1。如果你希望第一次renderCound.current为1,请使用react 17 谢谢!

import React, { useState, useRef, useEffect } from "react";

export default function App() {
  const [state, setState] = useState(0);
  const renderCount = useRef(0);
  useEffect(() => {
    renderCount.current = renderCount.current + 1;
  });

  return (
    <>
      <button onClick={() => setState(state + 3)}>Click to increment</button>
      {state}
      {renderCount.current}
    </>
  );
}


2
投票

在组件外部存储一个计数器。每次组件渲染时递增它。

let renderCount = 0;

export default function App(){
  const [state, setState] = useState(0);
  renderCount++;
  return <>
    <button onClick={() => setState(state + 3)}>Click to increment</button>
    {state}
    <p>This component has rendered {renderCount} times.</p>
  </>
}

请注意,有时组件可能会被渲染额外的时间(例如,对于严格模式测试)。


1
投票

我在其他帖子中看到了只需添加的选项

console.count('计数器')

在代码中使用,然后每次组件渲染时都会更新计数器


0
投票

如果您正在开发一个大项目,请创建一个自定义挂钩。通过这种方式,您可以解决不必要的渲染问题。

为 renderCount 创建自定义 Hook。

import { useRef, useEffect } from "react";

export default () => {
  const renderCount = useRef(0);
  useEffect(() => {
    renderCount.current++;
  });
  return renderCount.current;
};

然后从任何组件访问它。让我们看一下下面的例子。

function Counter() {
  const renderCount = useRenderCount();
  const [counter, setCounter] = useState(0);
  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>
        Counter value: {counter} | Render Count: {renderCount}
      </button>
    </div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.