简体   繁体   English

React Router v4路由器组件中的所有内容都会在每次路由更改时重新呈现

[英]React Router v4 everything in the Router component re-renders on every route change

I'm trying to understand better why all my components are re-rendering whenever a route changes in React Router v5. 我试图更好地理解为什么每当路由在React Router v5中更改时,我的所有组件都会重新渲染。 Note, these components are only re-rendering not re-mounting . 请注意,这些组件只是重新渲染而不是重新安装 When I open up the react extension in dev tools and select the Highlight Updates checkbox, I can see all my components get outlined when changing routes, even the components that are at a higher level than the route match: 当我在开发工具中打开react扩展并选中Highlight Updates复选框时,我可以看到在更改路线时所有组件都被勾勒出轮廓,即使是比路线匹配级别更高的组件也是如此:

<Router>
  <MyHeader />
  <ComponentWithRoutes />
</Router>

In this simple example, I would expect, that changing routes would not re-render the MyHeader component, since nothing changes. 在这个简单的示例中,我希望更改的路由不会重新呈现MyHeader组件,因为没有任何更改。 However I will still see a highlight with the dev tools. 但是,我仍然会看到dev工具的亮点。 I assume this is expected, since all the examples in the Docs exhibit the same behavior. 我认为这是预料之中的,因为文档中的所有示例都表现出相同的行为。

My question is two-fold. 我的问题有两个方面。 1) What is the actual cause of making a component like MyHeader to re-render? 1)使像MyHeader这样的组件重新渲染的真正原因是什么? It doesn't seem like any props or state are changing. 似乎没有任何道具或状态正在改变。 Is it because of the way the Router is using the Context API? 是因为路由器使用上下文API的方式? The Router is rendering and causing the children to re-render? 路由器正在渲染并导致子级重新渲染? 2) Why isn't this considered wasteful? 2)为什么不认为这是浪费? It seems like even though the actual DOM isn't changing, React would still have to go through the reconciliation steps in the virtual DOM. 即使实际的DOM并没有发生变化,React仍然必须经历虚拟DOM中的协调步骤。 Is it just so fast it's doesn't matter? 它是如此之快,没关系吗? What happens when you start having tons of nested components? 当您开始拥有大量嵌套组件时会发生什么?

Yup, this is the lay of the land. 是的,这是一块土地。

Your components will re-render unless they're React.PureComponent , or otherwise define shouldComponentUpdate() , when the parent component is re-rendered. 除非重新渲染父组件,否则您的组件将重新渲染,除非它们是React.PureComponent或以其他方式定义shouldComponentUpdate()

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

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