追踪为什么React组件被重新渲染

reactjs React.js

TomGO小小

2020-03-11

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

第786篇《追踪为什么React组件被重新渲染》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
小宇宙猪猪乐 2020.03.11

奇怪的是没有人给出这个答案,但是我发现它很有用,特别是因为道具更改几乎总是嵌套在深处。

勾子迷们:

import deep_diff from "deep-diff";
const withPropsChecker = WrappedComponent => {
  return props => {
    const prevProps = useRef(props);
    useEffect(() => {
      const diff = deep_diff.diff(prevProps.current, props);
      if (diff) {
        console.log(diff);
      }
      prevProps.current = props;
    });
    return <WrappedComponent {...props} />;
  };
};

“老”学校的迷们:

import deep_diff from "deep-diff";
componentDidUpdate(prevProps, prevState) {
      const diff = deep_diff.diff(prevProps, this.props);
      if (diff) {
        console.log(diff);
      }
}

PS我还是喜欢使用HOC(高阶分量),因为有时您在顶部分解了道具,而Jacob的解决方案不太适合

Disclaimer: No affiliation whatsoever with the package owner. Just clicking tens of times around to try to spot the difference in deeply nested objects is a pain in the.

Harry小哥 2020.03.11

现在在npm上有一个钩子可供使用:

https://www.npmjs.com/package/use-trace-update

(公开,我发表了)

老丝 2020.03.11

The above answers are very helpful, just in case if anyone is looking for a specfic method to detect the cause of rerender then I found this library redux-logger very helpful.

What you can do is add the library and enable diffing between state(it is there in the docs) like:

const logger = createLogger({
    diff: true,
});

And add the middleware in the store.

然后console.log()在要测试的组件的render函数中放置一个

然后您可以运行您的应用程序并检查控制台日志。只要有日志,它就会显示状态之间的差异(nextProps and this.props),您可以决定是否真的需要渲染在此处输入图片说明

它将与diff键相似于上图。

小小古一 2020.03.11

这是一些React组件将重新渲染的实例。

  • 父组件重新渲染
  • this.setState()在组件内调用这将触发以下组件的生命周期方法shouldComponentUpdate> componentWillUpdate> render>componentDidUpdate
  • 组件的更改props这将触发componentWillReceiveProps> shouldComponentUpdate> componentWillUpdate> render> componentDidUpdateconnect的方法react-redux触发该当存在在终极版存储适用的变化)
  • 调用this.forceUpdate类似于this.setState

您可以通过在内部执行检查shouldComponentUpdatefalse在不需要时返回来最小化组件的重新渲染

另一种方法是使用React.PureComponent 或无状态的组件。纯的和无状态的组件仅在其道具发生更改时才重新渲染。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android