React Rendering的视觉指南--它总是在重新渲染

When does a React component re-render? Is it when its state or props change?

React组件什么时候会重新渲染?是在其状态或道具发生变化时吗?

React components re-render in response to parent render

Take a look at the gif above 👆

看看上面的gif图吧 👆

The structure of the app is: App > A > B > C.

该应用程序的结构是:App > A > B > C

Here is a slightly simplified code:

下面是一个稍微简化的代码。

const App = () => { return ( <ComponentA /> )
} const ComponentA = () => <ComponentB />
const ComponentB = () => <ComponentC />

Components A, B, and C don’t have any props or state. Yet, they still re-render when the App renders.

组成部分 A, B,以及 C没有任何道具或状态。然而,当应用程序渲染时,它们仍然会重新渲染。

In normal rendering, React does not care whether “props changed” - it will render child components unconditionally just because the parent rendered!

在正常的渲染中,React并不关心 "道具是否改变"--它将无条件地渲染子组件,只是因为父组件已经渲染了。

Mark Erikson - A (Mostly) Complete Guide to React Rendering Behavior

Mark Erikson -React渲染行为的(大部分)完整指南

To illustrate this point further, let’s add a state to every component and track the behavior.

为了进一步说明这一点,让我们给每个组件添加一个状态并跟踪其行为。

The tree of react components. Each has a button that updates its state.

When the state of C changes, only C renders. But when the state of B changes, both B and C render. The B renders because its state updates, and C renders because its parent renders.

C的状态发生变化时,只有 C渲染。但当状态的 B的状态发生变化时,既 BC呈现。这 B渲染是因为它的状态更新,而 C渲染是因为它的父体渲染了。

When the state of A changes, A renders because of the state update, B renders because A rendered, and C renders because B rendered.

的状态发生变化时 A发生变化。 A会因为状态的更新而呈现。 B渲染,因为 A呈现,而 C渲染,因为 B渲染了。

Avoiding re-renders

避免重蹈覆辙

There are several ways to avoid unnecessary re-renders in React. In this article, I will only focus on React.memo and save other methods for future posts. If you are interested in alternatives to memo check out Dan Abramov’s Before you memo().

在React中,有几种方法可以避免不必要的重现。在这篇文章中,我将只关注React.memo ,其他方法留待以后的文章中讨论。如果你对memo 的替代方法感兴趣,请查阅Dan Abramov的Before you memo()

Also please keep in mind that in this post, I only explore re-renders caused by direct state update, or parent render. I don't pass any props.

另外,请记住,在这篇文章中,我只探讨了由直接状态更新或父级渲染引起的重新渲染。我没有传递任何道具。

If you wrap a component in memo, it won...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.124.0. UTC+08:00, 2024-05-03 07:44
浙ICP备14020137号-1 $访客地图$