理想情况下,我希望在每个组件中放置一个小圆组件,并在屏幕上看到渲染计数。
如何使用钩子/函数组件跟踪重新渲染?
发布于 2020-03-23 03:25:35
好了,回到这个问题上来,找出一些对我的目的有效的东西。
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;(使用SHOW_RENDER_COUNTERS全局显示/隐藏计数器。)
然后将其内联到要跟踪的组件中。
const Bubble = () => {
const renderCounter = useRenderCounter();
return (
<>
<BubbleCoomponentCode />
{renderCounter}
</>
);
};最终会得到这样的结果。

https://stackoverflow.com/questions/60470891
复制相似问题