gpt4 book ai didi

reactjs - 追踪 React 组件重新渲染的原因

转载 作者:行者123 更新时间:2023-12-03 12:52:46 31 4
gpt4 key购买 nike

是否有系统的方法来调试导致组件在 React 中重新渲染的原因?我放置了一个简单的 console.log() 来查看它渲染了多少次,但我很难弄清楚是什么导致组件渲染多次,即在我的情况下(4 次)。是否存在显示时间线和/或所有组件树渲染和顺序的工具?

最佳答案

如果您想要一个没有任何外部依赖项的简短片段,我发现这很有用

componentDidUpdate(prevProps, prevState) {
Object.entries(this.props).forEach(([key, val]) =>
prevProps[key] !== val && console.log(`Prop '${key}' changed`)
);
if (this.state) {
Object.entries(this.state).forEach(([key, val]) =>
prevState[key] !== val && console.log(`State '${key}' changed`)
);
}
}

这是我用来跟踪功能组件更新的一个小钩子(Hook)

function useTraceUpdate(props) {
const prev = useRef(props);
useEffect(() => {
const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
if (prev.current[k] !== v) {
ps[k] = [prev.current[k], v];
}
return ps;
}, {});
if (Object.keys(changedProps).length > 0) {
console.log('Changed props:', changedProps);
}
prev.current = props;
});
}

// Usage
function MyComponent(props) {
useTraceUpdate(props);
return <div>{props.children}</div>;
}

关于reactjs - 追踪 React 组件重新渲染的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004631/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com