你如何在 React Native 中跟踪“函数组件”的渲染计数?

Gol*_*Jer 1 react-native

理想情况下,我想在每个组件中放置一个小圆组件并在屏幕上查看渲染计数。

您如何使用钩子/功能组件跟踪重新渲染?

Gol*_*Jer 7

好的,回到这个问题并找出适合我的目的的东西。

import React, { useRef } from 'react';
import { TextInput } from 'react-native';

const SHOW_RENDER_COUNTERS = true;

const useRenderCounter = () => {
  const renderCount = useRef(0);
  renderCount.current = renderCount.current + 1;

  if (__DEV__ && SHOW_RENDER_COUNTERS) {
    return (
      <TextInput
        style={{
          backgroundColor: 'hsl(0, 100%, 50%)',
          borderRadius: 6,
          color: 'hsl(0, 0%, 100%)',
          fontSize: 10,
          fontWeight: 'bold',
          height: 35,
          margin: 2,
          textAlign: 'center',
          width: 35,
        }}
        value={String(renderCount.current)}
      />
    );
  }
  return null;
};

export default useRenderCounter;
Run Code Online (Sandbox Code Playgroud)

SHOW_RENDER_COUNTERS用于全局显示/隐藏计数器。)

然后将其内联到要跟踪的组件中。

const Bubble = () => {
  const renderCounter = useRenderCounter();

  return (
    <>
      <BubbleCoomponentCode />
      {renderCounter}
    </>
  );
};
Run Code Online (Sandbox Code Playgroud)

并最终得到这样的结果。