React Rendering的视觉指南--道具

The Child component is wrapped in memo. Its props don’t change. Why does it still re-render when Parent renders?

子组件被包裹在memo 。它的道具并没有改变。为什么当Parent渲染的时候,它还是会重新渲染?

Two components Parent and Child. Parent passes a prop {display: 'flex'} to the Child. Child re-renders every time parent renders

There are two types of values in javascript. Understanding the differences between them gives you Jedi powers in controlling component rendering.

在javascript中,有两种类型的值。了解它们之间的区别,就能在控制组件的渲染方面获得绝妙的权力。

Yoda

This article is a second chapter of "A Visual Guide To React Rendering". If you haven't yet, check out the first chapter It always re-renders.

本文是《A Visual Guide To React Rendering》的第二章。如果你还没有,请查看第一章它总是在重新渲染

Primitives

基本原理

The first type of value is primitive. Let’s try to pass a primitive value as a prop to the Child.

第一种类型的值是原始的。让我们试着把一个原始值作为一个道具传递给Child。

Two components Parent and Child. Parent passes a prop name='Alex' to the Child. Child doesn't re-render when parent renders

The Child is wrapped in memo. This means it will only re-render when its props change. The way memo determines if props changed is by shallow comparison prevProp === nextProp. Since "Alex" is a string, which is a primitive value, this comparison will return true, and the component won’t re-render. You can check it by yourself, paste this in your browser console "Alex" === "Alex".

Child被包裹在memo 。这意味着它只有在其道具发生变化时才会重新渲染。memo 判断道具是否改变的方法是通过浅层比较prevProp === nextProp 。由于"Alex" 是一个字符串,是一个原始值,这种比较将返回true ,并且组件不会重新渲染。你可以自己检查,把这个粘贴到你的浏览器控制台"Alex" === "Alex"

Non-primitives

非原住民

The second type of value is non-primitive. Here we pass the object as a prop. The object is a non-primitive value. So why does a non-primitive value makes the Child re-render?

第二种类型的值是非主观的。这里我们把对象作为一个道具来传递。该对象是一个非原始值。那么,为什么非原始值会使Child重新渲染?

Two components Parent and Child. Parent passes a prop {display: 'flex'} to the Child. Child re-renders every time parent renders

Remember, to decide if the props changed, memo does the shallow comparison. When you compare two non-primitives like that {display: "flex"} === {display: "flex"}, the result will always be false. You can check it in your browser console.

记住,为了决定道具是否改变,memo 进行浅层比较。当你像这样比较两个非原语{display: "flex"} === {display: "flex"} ,结果将总是false 。你可以在你的浏览器控制台中检查。

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference wi...

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

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