简体   繁体   English

为什么 React 组件会渲染?

[英]Why does the React component render?

I have a rather complicated React app.我有一个相当复杂的 React 应用程序。 The problem I am facing is that when a link is click on in the navbar the navbar re-renders.我面临的问题是,当在导航栏中单击链接时,导航栏会重新呈现。 Obviously this is a sign that the app is doing unnecessary rendering.显然,这表明应用程序正在进行不必要的渲染。 The navbar exists in a "header" component.导航栏存在于“标题”组件中。 This "header" should be fixed.这个“标题”应该是固定的。 But it is getting called numerous times.但它被多次调用。 What is the recommended way to tell WHY a component renders.告诉组件为什么呈现的推荐方法是什么。 I can think of numerous reasons and I would like to start eliminating them to cut down on unnecessary renders.我可以想到很多原因,我想开始消除它们以减少不必要的渲染。 The component could be该组件可以是

  • Changing internal state (via useState)更改内部 state(通过 useState)
  • useEffect使用效果
  • subscribed to "external" state via useSelect通过 useSelect 订阅了“外部”state
  • have props change有道具改变

There may be others.可能还有其他人。 How do I tell WHY a component renders?我如何知道组件为何呈现?

There (apparently) is no easy way to tell why a component renders, probably because it inherently requires deep comparison (at least to cover all cases), which can be an expensive operation. (显然)没有简单的方法来说明组件为何呈现,可能是因为它本质上需要深度比较(至少要涵盖所有情况),这可能是一项昂贵的操作。

But there are many tools and workarounds.但是有很多工具和解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM