diff --git a/beta/scripts/generateRedirects.js b/beta/scripts/generateRedirects.js
index b6e23b58aa..92c4d9e101 100644
--- a/beta/scripts/generateRedirects.js
+++ b/beta/scripts/generateRedirects.js
@@ -42,7 +42,7 @@ function writeRedirectsFile(redirects, redirectsFilePath) {
* Make sure we dont have the same redirect already
*/
oldConfigContent.redirects.forEach((data) => {
- if(vercelRedirects[data.source]){
+ if (vercelRedirects[data.source]) {
delete vercelRedirects[data.source];
}
});
diff --git a/beta/scripts/headingIDHelpers/validateHeadingIDs.js b/beta/scripts/headingIDHelpers/validateHeadingIDs.js
index 535613e7fb..5d400178f1 100644
--- a/beta/scripts/headingIDHelpers/validateHeadingIDs.js
+++ b/beta/scripts/headingIDHelpers/validateHeadingIDs.js
@@ -17,9 +17,7 @@ function validateHeaderId(line) {
const match = /\{\/\*(.*?)\*\/}/.exec(line);
const id = match;
if (!id) {
- console.error(
- 'Run yarn fix-headings to generate headings.'
- );
+ console.error('Run yarn fix-headings to generate headings.');
process.exit(1);
}
}
diff --git a/beta/scripts/headingIDHelpers/walk.js b/beta/scripts/headingIDHelpers/walk.js
index 721274e096..54cd500ca3 100644
--- a/beta/scripts/headingIDHelpers/walk.js
+++ b/beta/scripts/headingIDHelpers/walk.js
@@ -2,10 +2,10 @@ const fs = require('fs');
module.exports = function walk(dir) {
let results = [];
- /**
+ /**
* If the param is a directory we can return the file
*/
- if(dir.includes('md')){
+ if (dir.includes('md')) {
return [dir];
}
const list = fs.readdirSync(dir);
diff --git a/beta/scripts/headingIdLinter.js b/beta/scripts/headingIdLinter.js
index 037e4945f0..6b8f75fc71 100644
--- a/beta/scripts/headingIdLinter.js
+++ b/beta/scripts/headingIdLinter.js
@@ -1,12 +1,12 @@
const validateHeaderIds = require('./headingIDHelpers/validateHeadingIDs');
const generateHeadingIds = require('./headingIDHelpers/generateHeadingIDs');
-/**
+/**
* yarn lint-heading-ids --> Checks all files and causes an error if heading ID is missing
* yarn lint-heading-ids --fix --> Fixes all markdown file's heading IDs
* yarn lint-heading-ids path/to/markdown.md --> Checks that particular file for missing heading ID (path can denote a directory or particular file)
* yarn lint-heading-ids --fix path/to/markdown.md --> Fixes that particular file's markdown IDs (path can denote a directory or particular file)
-*/
+ */
const markdownPaths = process.argv.slice(2);
if (markdownPaths.includes('--fix')) {
diff --git a/beta/src/pages/learn/preserving-and-resetting-state.md b/beta/src/pages/learn/preserving-and-resetting-state.md
index 5497d2e17b..a716968c47 100644
--- a/beta/src/pages/learn/preserving-and-resetting-state.md
+++ b/beta/src/pages/learn/preserving-and-resetting-state.md
@@ -1,44 +1,48 @@
---
-title: Preserving and Resetting State
+title: 对 state 进行保留和重置
+translators:
+ - YogaLin
+ - Neo42
+ - QC-L
---
-State is isolated between components. React keeps track of which state belongs to which component based on their place in the UI tree. You can control when to preserve state and when to reset it between re-renders.
+各个组件的 state 是各自独立的。根据组件在 UI 树中的位置,React 可以跟踪哪些 state 属于哪个组件。你可以控制在重新渲染过程中何时对 state 进行保留和重置。
-* How React "sees" component structures
-* When React chooses to preserve or reset the state
-* How to force React to reset component's state
-* How keys and types affect whether the state is preserved
+* React 如何“处理”组件结构
+* React 何时选择保留或重置 state
+* 如何强制 React 重置组件的 state
+* key 和组件类型如何影响 state 是否被保留
-## The UI tree {/*the-ui-tree*/}
+## UI 树 {/*the-ui-tree*/}
-Browsers use many tree structures to model UI. The [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) represents HTML elements, the [CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model) does the same for CSS. There's even an [Accessibility tree](https://developer.mozilla.org/docs/Glossary/Accessibility_tree)!
+浏览器使用许多树形结构来为 UI 建立模型。[DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) 用于表示 HTML 元素,[CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model) 则表示 CSS 元素。甚至还有 [Accessibility tree](https://developer.mozilla.org/docs/Glossary/Accessibility_tree)!
-React also uses tree structures to manage and model the UI you make. React makes **UI trees** from your JSX. Then React DOM updates the browser DOM elements to match that UI tree. (React Native translates these trees into elements specific to mobile platforms.)
+React 也使用树形结构来对你创造的 UI 进行管理和建模。React 根据你的 JSX 生成 **UI 树**。React DOM 根据 UI 树去更新浏览器的 DOM 元素。(React Native 则将这些 UI 树转译成移动平台上特有的元素。)
-From components, React creates a UI tree which React DOM uses to render the DOM
+React 会根据组件创建了一棵 UI 树,React DOM 用它来渲染 DOM
-## State is tied to a position in the tree {/*state-is-tied-to-a-position-in-the-tree*/}
+## state 与树中的某个位置相关联 {/*state-is-tied-to-a-position-in-the-tree*/}
-When you give a component state, you might think the state "lives" inside the component. But the state is actually held inside React. React associates each piece of state it's holding with the correct component by where that component sits in the UI tree.
+当你为一个组件添加 state 时,你可能会觉得 state “活”在组件内部。但实际上,state 被保存在 React 内部。根据组件在 UI 树中的位置,React 将它所持有的每个 state 与正确的组件关联起来。
-Here, there is only one `` JSX tag, but it's rendered at two different positions:
+下面只定义了一个 `` JSX 标签,但将它渲染在了两个不同的位置:
@@ -72,7 +76,7 @@ function Counter() {
>
{score}
);
@@ -102,23 +106,23 @@ label {
-Here's how these look as a tree:
+下面是它们的树形结构的样子:
-React tree
+React 树
-**These are two separate counters because each is rendered at its own position in the tree.** You don't usually have to think about these positions to use React, but it can be useful to understand how it works.
+**这是两个独立的 counter,因为它们在树中被渲染在了各自的位置。** 一般情况下你不用去考虑这些位置来使用 React,但知道它们是如何工作会很有用。
-In React, each component on the screen has fully isolated state. For example, if you render two `Counter` components side by side, each of them will get its own, independent, `score` and `hover` states.
+在 React 中,屏幕中的每个组件都有完全独立的 state。举个例子,当你并排渲染两个 `Counter` 组件时,它们都会拥有各自独立的 `score` 和 `hover` state。
-Try clicking both counters and notice they don't affect each other:
+试试点击两个 counter 你会发现它们互不影响:
@@ -151,7 +155,7 @@ function Counter() {
>
{score}
);
@@ -176,7 +180,7 @@ function Counter() {
-As you can see, when one counter is updated, only the state for that component is updated:
+如你所见,当一个计数器被更新时,只有该组件的状态会被更新:
@@ -190,7 +194,7 @@ Updating state
-React will keep the state around for as long as you render the same component at the same position. To see this, increment both counters, then remove the second component by unchecking "Render the second counter" checkbox, and then add it back by ticking it again:
+只有当你在相同的位置渲染相同的组件时,React 才会一直保留着组件的 state。想要验证这一点,可以将两个计数器的值递增,取消勾选 “渲染第二个计数器” 复选框,然后再次勾选它:
@@ -211,7 +215,7 @@ export default function App() {
setShowB(e.target.checked)
}}
/>
- Render the second counter
+ 渲染第二个计数器
);
@@ -234,7 +238,7 @@ function Counter() {
>
{score}
);
@@ -264,35 +268,35 @@ label {
-Notice how the moment you stop rendering the second counter, its state disappears completely. That's because when React removes a component, it destroys its state.
+注意,当你停止渲染第二个计数器的那一刻,它的 state 完全消失了。这是因为 React 在移除一个组件时,也会销毁它的 state。
-Deleting a component
+删除组件
-When you tick "Render the second counter," a second `Counter` and its state are initialized from scratch (`score = 0`) and added to the DOM.
+当你重新勾选“渲染第二个计数器”复选框时,另一个计数器及其 state 将从头开始初始化(`score = 0`)并被添加到 DOM 中。
-Adding a component
+添加组件
-**React preserves a component's state for as long as it's being rendered at its position in the UI tree.** If it gets removed, or a different component gets rendered at the same position, React discards its state.
+**只要一个组件还被渲染在 UI 树的相同位置,React 就会保留它的 state。** 如果它被移除,或者一个不同的组件被渲染在相同的位置,那么 React 就会丢掉它的 state。
-## Same component at the same position preserves state {/*same-component-at-the-same-position-preserves-state*/}
+## 相同位置的相同组件会使得 state 被保留下来 {/*same-component-at-the-same-position-preserves-state*/}
-In this example, there are two different `` tags:
+在这个例子中,有两个不同的 `` 标签:
@@ -316,7 +320,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ 使用好看的样式
);
@@ -342,7 +346,7 @@ function Counter({ isFancy }) {
>
{score}
);
@@ -377,24 +381,24 @@ label {
-When you tick or clear the checkbox, the counter state does not get reset. Whether `isFancy` is `true` or `false`, you always have a `` as the first child of the `div` returned from the root `App` component:
+当你勾选或清空复选框的时候,计数器 state 并没有被重置。不管 `isFancy` 是 `true` 还是 `false`,根组件 `App` 返回的 `div` 的第一个子组件都是 ``:
-Updating the `App` state does not reset the `Counter` because `Counter` stays in the same position
+更新 `App` 的状态不会重置 `Counter`,因为 `Counter` 始终保持在同一位置。
-It's the same component at the same position, so from React's perspective, it's the same counter.
+它是位于相同位置的相同组件,所以对 React 来说,它是同一个计数器。
-Remember that **it's the position in the UI tree--not in the JSX markup--that matters to React!** This component has two `return` clauses with different `` JSX tags inside and outside the `if`:
+记住 **对 React 来说重要的是组件在 UI 树中的位置,而不是在 JSX 中的位置!** 这个组件在 `if` 内外有两个`return` 语句,它们带有不同的 `` JSX 标签:
@@ -415,7 +419,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ 使用好看的样式
);
@@ -431,7 +435,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ 使用好看的样式
);
@@ -457,7 +461,7 @@ function Counter({ isFancy }) {
>
{score}
);
@@ -492,15 +496,15 @@ label {
-You might expect the state to reset when you tick checkbox, but it doesn't! This is because **both of these `` tags are rendered at the same position.** React doesn't know where you place the conditions in your function. All it "sees" is the tree you return. In both cases, the `App` component returns a `
` with `` as a first child. This is why React considers them as _the same_ ``.
+你可能以为当你勾选复选框的时候 state 会被重置,但它并没有!这是因为 **两个 `` 标签被渲染在了相同的位置。** React 不知道你的函数里是如何进行条件判断的,它只会“看到”你返回的树。在这两种情况下,`App` 组件都会返回一个包裹着 `` 作为第一个子组件的 `div`。这就是 React 认为它们是 _同一个_ `` 的原因。
-You can think of them as having the same "address": the first child of the first child of the root. This is how React matches them up between the previous and next renders, regardless of how you structure your logic.
+你可以认为它们有相同的“地址”:根组件的第一个子组件的第一个子组件。不管你的逻辑是怎么组织的,这就是 React 在前后两次渲染之间将它们进行匹配的方式。
-## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/}
+## 相同位置的不同组件会使 state 重置 {/*different-components-at-the-same-position-reset-state*/}
-In this example, ticking the checkbox will replace `` with a `
) : (
)}
@@ -524,7 +528,7 @@ export default function App() {
setIsPaused(e.target.checked)
}}
/>
- Take a break
+ 休息一下
);
@@ -547,7 +551,7 @@ function Counter() {
>
{score}
);
@@ -577,13 +581,13 @@ label {
-Here, you switch between _different_ component types at the same position. Initially, the first child of the `
` contained a `Counter`. But when you swapped in a `p`, React removed the `Counter` from the UI tree and destroyed its state.
+示例中,你在相同位置对 _不同_ 的组件类型进行切换。刚开始 `
` 的第一个子组件是一个 `Counter`。但是当你切换成 `p` 时,React 将 `Counter` 从 UI 树中移除了并销毁了它的状态。
-When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added
+当 `Counter` 变为 `p` 时,`Counter` 会被移除,同时 `p` 被添加。
@@ -593,13 +597,13 @@ When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added
-When switching back, the `p` is deleted and the `Counter` is added
+当切换回来时,`p` 会被删除,而 `Counter` 会被添加
-Also, **when you render a different component in the same position, it resets the state of its entire subtree**. To see how this works, increment the counter and then tick the checkbox:
+并且,**当你在相同位置渲染不同的组件时,组件的整个子树都会被重置**。要验证这一点,可以增加计数器的值然后勾选复选框:
@@ -627,7 +631,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ 使用好看的样式
);
@@ -688,13 +692,13 @@ label {
-The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `div` to a `section`. When the child `div` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
+当你勾选复选框后计数器的 state 被重置了。虽然你渲染了一个 `Counter`,但是 `div` 的第一个子组件从 `div` 变成了 `section`。当子组件 `div` 从 DOM 中被移除的时候,它底下的整棵树(包含 `Counter` 以及它的 state)也都被销毁了。
-When `section` changes to `div`, the `section` is deleted and the new `div` is added
+当 `section` 变为 `div` 时,`section` 会被删除,新的 `div` 被添加
@@ -704,19 +708,19 @@ When `section` changes to `div`, the `section` is deleted and the new `div` is a
-When switching back, the `div` is deleted and the new `section` is added
+当切换回来时,`div` 会被删除,新的 `section` 被添加
-As a rule of thumb, **if you want to preserve the state between re-renders, the structure of your tree needs to "match up"** from one render to another. If the structure is different, the state gets destroyed because React destroys state when it removes a component from the tree.
+一般来说,**如果你想在重新渲染时保留 state,几次渲染中的树形结构就应该相互“匹配”**。结构不同就会导致 state 的销毁,因为 React 会在将一个组件从树中移除时销毁它的 state。
-This is why you should not nest component function definitions.
+以下是为什么你不应该把组件函数的定义嵌套起来的原因。
-Here, the `MyTextField` component function is defined *inside* `MyComponent`:
+示例中, `MyTextField` 组件被定义在 `MyComponent` *内部*:
@@ -742,7 +746,7 @@ export default function MyComponent() {
+ }}>点击了 {counter} 次
>
);
}
@@ -751,13 +755,13 @@ export default function MyComponent() {
-Every time you click the button, the input state disappears! This is because a *different* `MyTextField` function is created for every render of `MyComponent`. You're rendering a *different* component in the same position, so React resets all state below. This leads to bugs and performance problems. To avoid this problem, **always declare component functions at the top level, and don't nest their definitions.**
+每次你点击按钮,输入框的 state 都会消失!这是因为每次 `MyComponent` 渲染时都会创建一个 _不同_ 的 `MyTextField` 函数。你在相同位置渲染的是 _不同_ 的组件,所以 React 将其下所有的 state 都重置了。这样会导致 bug 以及性能问题。为了避免这个问题, **永远要将组件定义在最上层并且不要把它们的定义嵌套起来。**
-## Resetting state at the same position {/*resetting-state-at-the-same-position*/}
+## 在相同位置重置 state {/*resetting-state-at-the-same-position*/}
-By default, React preserves state of a component while it stays at the same position. Usually, this is exactly what you want, so it makes sense as the default behavior. But sometimes, you may want to reset a component's state. Consider this app that lets two players keep track of their scores during each turn:
+默认情况下,React 会在一个组件保持在同一位置时保留它的 state。通常这就是你想要的,所以把它作为默认特性很合理。但有时候,你可能想要重置一个组件的 state。考虑一下这个应用,它可以让两个玩家在每个回合中记录他们的得分:
@@ -776,7 +780,7 @@ export default function Scoreboard() {
);
@@ -797,9 +801,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
{person} 的分数:{score}
);
@@ -827,19 +831,19 @@ h1 {
-Currently, when you change the player, the score is preserved. The two `Counter`s appear in the same position, so React sees them as *the same* `Counter` whose `person` prop has changed.
+目前当你切换玩家时,分数会被保留下来。这两个 `Counter` 出现在相同的位置,所以 React 会认为它们是 _同一个_ `Counter`,只是传了不同的 `person` prop。
-But conceptually, in this app they should be two separate counters. They might appear in the same place in the UI, but one is a counter for Taylor, and another is a counter for Sarah.
+但是从概念上讲,这个应用中的两个计数器应该是各自独立的。虽然它们在 UI 中的位置相同,但是一个是 Taylor 的计数器,一个是 Sarah 的计数器。
-There are two ways to reset state when switching between them:
+有两个方法可以在它们相互切换时重置 state:
-1. Render components in different positions
-2. Give each component an explicit identity with `key`
+1. 将组件渲染在不同的位置
+2. 使用 `key` 赋予每个组件一个明确的身份
-### Option 1: Rendering a component in different positions {/*option-1-rendering-a-component-in-different-positions*/}
+### 方法一:将组件渲染在不同的位置 {/*option-1-rendering-a-component-in-different-positions*/}
-If you want these two `Counter`s to be independent, you can render them in two different positions:
+你如果想让两个 `Counter` 各自独立的话,可以将它们渲染在不同的位置:
@@ -859,7 +863,7 @@ export default function Scoreboard() {
);
@@ -880,9 +884,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
{person} 的分数:{score}
);
@@ -910,8 +914,8 @@ h1 {
-* Initially, `isPlayerA` is `true`. So the first position contains `Counter` state, and the second one is empty.
-* When you click the "Next player" button the first position clears but the second one now contains a `Counter`.
+* 起初 `isPlayerA` 的值是 `true`。所以第一个位置包含了 `Counter` 的 state,而第二个位置是空的。
+* 当你点击“下一位玩家”按钮时,第一个位置会被清空,而第二个位置现在包含了一个 `Counter`。
@@ -935,17 +939,17 @@ Clicking "next" again
-> Each `Counter`'s state gets destroyed each time its removed from the DOM. This is why they reset every time you click the button.
+> 每次一个 `Counter` 被从 DOM 中移除时,它的 state 就会被销毁。这就是每次你点击按钮时它们就会被重置的原因。
-This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX.
+这个解决方案在你只有少数几个独立的组件渲染在相同的位置时会很方便。这个例子中只有 2 个组件,所以在 JSX 里将它们分开进行渲染并不麻烦。
-### Option 2: Resetting state with a key {/*option-2-resetting-state-with-a-key*/}
+### 方法二:使用 key 来重置 state {/*option-2-resetting-state-with-a-key*/}
-There is also another, more generic, way to reset a component's state.
+还有另一种更通用的重置组件 state 的方法。
-You might have seen `key`s when [rendering lists](/learn/rendering-lists#keeping-list-items-in-order-with-key). Keys aren't just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent ("first counter", "second counter") to discern between components. But keys let you tell React that this is not just a *first* counter, or a *second* counter, but a specific counter--for example, *Taylor's* counter. This way, React will know *Taylor's* counter wherever it appears in the tree!
+你可能在 [渲染列表](/learn/rendering-lists#keeping-list-items-in-order-with-key) 时见到过 `key`。但 key 不只可以用于列表!你可以使用 key 来让 React 区分任何组件。默认情况下,React 使用父组件内部的顺序(“第一个计数器”、“第二个计数器”)来区分组件。但是 key 可以让你告诉 React 这不仅仅是 *第一个* 或者 *第二个* 计数器,而且还是一个特定的计数器——例如,*Taylor 的* 计数器。这样无论它出现在树的任何位置, React 都会知道它是 *Taylor 的* 计数器!
-In this example, the two ``s don't share state even though they appear in the same place in JSX:
+在这个例子中,即使两个 `` 会出现在 JSX 中的同一个位置,它们也不会共享 state:
@@ -964,7 +968,7 @@ export default function Scoreboard() {
);
@@ -985,9 +989,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
{person} 的分数:{score}
);
@@ -1015,7 +1019,7 @@ h1 {
-Switching between Taylor and Sarah does not preserve the state. This is because **you gave them different `key`s:**
+在 Taylor 和 Sarah 之间切换不会使 state 被保留下来。因为 **你给他们赋了不同的 `key`:**
```js
{isPlayerA ? (
@@ -1025,15 +1029,15 @@ Switching between Taylor and Sarah does not preserve the state. This is because
)}
```
-Specifying a `key` tells React to use the `key` itself as part of the position, instead of their order within the parent. This is why, even though you render them in the same place in JSX, from React's perspective, these are two different counters. As a result, they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed. Toggling between them resets their state over and over.
+指定一个 `key` 能够让 React 将 `key` 本身而非它们在父组件中的顺序作为位置的一部分。这就是为什么尽管你用 JSX 将组件渲染在相同位置,但在 React 看来它们是两个不同的计数器。因此它们永远都不会共享 state。每当一个计数器出现在屏幕上时,它的 state 会被创建出来。每当它被移除时,它的 state 就会被销毁。在它们之间切换会一次又一次地使它们的 state 重置。
-> Remember that keys are not globally unique. They only specify the position *within the parent*.
+> 请记住 key 不是全局唯一的。它们只能指定 **父组件内部** 的顺序。
-### Resetting a form with a key {/*resetting-a-form-with-a-key*/}
+### 使用 key 重置表单 {/*resetting-a-form-with-a-key*/}
-Resetting state with a key is particularly useful when dealing with forms.
+使用 key 来重置 state 在处理表单时特别有用。
-In this chat app, the `` component contains the text input state:
+在这个聊天应用中, `` 组件包含文本输入 state:
@@ -1096,11 +1100,11 @@ export default function Chat({ contact }) {
);
}
@@ -1128,17 +1132,17 @@ textarea {
-Try entering something into the input, and then press "Alice" or "Bob" to choose a different recipient. You will notice that the input state is preserved because the `` is rendered at the same position in the tree.
+尝试在输入框中输入一些内容,然后点击 “Alice” 或 “Bob” 来选择不同的收件人。你会发现因为 `` 被渲染在了树的相同位置,输入框的 state 被保留下来了。
-**In many apps, this may be the desired behavior, but not in a chat app!** You don't want to let the user send a message they already typed to a wrong person due to an accidental click. To fix it, add a `key`:
+**在很多应用里这可能会是大家所需要的特性,但在这个聊天应用里并不是!** 你不应该让用户因为一次偶然的点击而把他们已经输入的信息发送给一个错误的人。要修复这个问题,只需给组件添加一个 `key` :
```js
```
-This ensures that when you select a different recipient, the `Chat` component will be recreated from scratch, including any state in the tree below it. React will also re-create the DOM elements instead of reusing them.
+这样确保了当你选择一个不同的收件人时, `Chat` 组件——包括其下方树中的任何 state——都将从头开始重新创建。 React 还将重新创建 DOM 元素,而不是复用它们。
-Now switching the recipient always clears the text field:
+现在切换收件人就总会清除文本字段了:
@@ -1201,11 +1205,11 @@ export default function Chat({ contact }) {
);
}
@@ -1233,24 +1237,25 @@ textarea {
-
+
-In a real chat app, you'd probably want to recover the input state when the user selects the previous recipient again. There are a few ways to keep the state "alive" for a component that's no longer visible:
+在真正的聊天应用中,你可能会想在用户再次选择前一个收件人时恢复输入 state。对于一个不可见的组件,有几种方法可以让它的 state “活下去”:
-- You could render _all_ chats instead of just the current one, but hide all the others with CSS. The chats would not get removed from the tree, so their local state would be preserved. This solution works great for simple UIs. But it can get very slow if the hidden trees are large and contain a lot of DOM nodes.
-- You could [lift the state up](/learn/sharing-state-between-components) and hold the pending message for each recipient in the parent component. This way, when the child components get removed, it doesn't matter, because it's the parent that keeps the important information. This is the most common solution.
-- You might also use a different source in addition to React state. For example, you probably want a message draft to persist even if the user accidentally closes the page. To implement this, you could have the `Chat` component initialize its state by reading from the [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), and save the drafts there too.
+- 与其只渲染现在这一个聊天,你可以把 _所有_ 聊天都渲染出来,但用 CSS 把其他聊天隐藏起来。这些聊天就不会从树中被移除了,所以它们的内部 state 会被保留下来。这种解决方法对于简单 UI 非常有效。但如果要隐藏的树形结构很大且包含了大量的 DOM 节点,那么性能就会变得很差。
+- 你可以进行 [状态提升](/learn/sharing-state-between-components) 并在父组件中保存每个收件人的草稿消息。这样即使子组件被移除了也无所谓,因为保留重要信息的是父组件。这是最常见的解决方法。
+- 除了 React 的 state,你也可以使用其他数据源。例如,也许你希望即使用户不小心关闭页面也可以保存一份信息草稿。要实现这一点,你可以让 `Chat` 组件通过读取 [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) 对其 state 进行初始化,并把草稿保存在那里。
-No matter which strategy you pick, a chat _with Alice_ is conceptually distinct from a chat _with Bob_, so it makes sense to give a `key` to the `` tree based on the current recipient.
+无论采取哪种策略,_与 Alice_ 的聊天在概念上都不同于 _与 Bob_ 的聊天,因此根据当前收件人为 `` 树指定一个 `key` 是合理的。
-- React keeps state for as long as the same component is rendered at the same position.
-- State is not kept in JSX tags. It's associated with the tree position in which you put that JSX.
-- You can force a subtree to reset its state by giving it a different key.
-- Don't nest component definitions, or you'll reset state by accident.
+- 只要在相同位置渲染的是相同组件, React 就会保留状态。
+- state 不会被保存在 JSX 标签里。它与你在树中放置该 JSX 的位置相关联。
+- 你可以通过为一个子树指定一个不同的 key 来重置它的 state。
+- 不要嵌套组件的定义,否则你会意外地导致 state 被重置。
+
@@ -1258,9 +1263,9 @@ No matter which strategy you pick, a chat _with Alice_ is conceptually distinct
-### Fix disappearing input text {/*fix-disappearing-input-text*/}
+### 修复丢失的输入框文本 {/*fix-disappearing-input-text*/}
-This example shows a message when you press the button. However, pressing the button also accidentally resets the input. Why does this happen? Fix it so that pressing the button does not reset the input text.
+这个例子在你按下按钮时会展示一条消息,但同时也会意外地重置输入框。为什么会发生这种情况?修复它,使按下按钮不再导致输入框文本重置。
@@ -1272,11 +1277,11 @@ export default function App() {
if (showHint) {
return (
-
Hint: Your favorite city?
+
提示:你最喜欢的城市?
+ }}>隐藏提示
);
}
@@ -1285,7 +1290,7 @@ export default function App() {
+ }}>显示提示
);
}
@@ -1309,9 +1314,9 @@ textarea { display: block; margin: 10px 0; }
-The problem is that `Form` is rendered in different positions. In the `if` branch, it is the second child of the `
`, but in the `else` branch, it is the first child. Therefore, the component type in each position changes. The first position changes between holding a `p` and a `Form`, while the second position changes between holding a `Form` and a `button`. React resets the state every time the component type changes.
+问题在于 `Form` 被渲染在了不同的位置。在 `if` 分支里,`Form` 是 `
` 的第二个子组件,但在 `else` 分支里它是第一个子组件。所以相同位置的组件类型发生了变化。第一个位置时而包含一个 `p`,时而包含一个 `Form`;而第二个位置时而包含一个 `Form`,时而包含一个 `button`。每当组件类型发生变化时, React 都会重置 state。
-The easiest solution is to unify the branches so that `Form` always renders in the same position:
+最简单的解决方案是将各个分支合并,这样 `Form` 就总会在相同位置渲染:
@@ -1323,17 +1328,17 @@ export default function App() {
return (
{showHint &&
-
Hint: Your favorite city?
+
提示:你最喜欢的城市?
}
{showHint ? (
+ }}>隐藏提示
) : (
+ }}>显示提示
)}
);
@@ -1357,7 +1362,7 @@ textarea { display: block; margin: 10px 0; }
-Technically, you could also add `null` before `` in the `else` branch to match the `if` branch structure:
+其实,你还可以在 `else` 分支的 `` 之前加个 `null`,以匹配 `if` 分支的结构:
@@ -1369,11 +1374,11 @@ export default function App() {
if (showHint) {
return (
);
}
@@ -1405,19 +1410,19 @@ textarea { display: block; margin: 10px 0; }
-This way, `Form` is always the second child, so it stays in the same position and keeps its state. But this approach is much less obvious and introduces a risk that someone else will remove that `null`.
+这样 `Form` 就会始终是第二个子组件,所以它就会保持在相同位置并保留它的 state。但是这种方法特别不明显,并会引入一个风险因素——其他人可能会删除那个 `null`。
-### Swap two form fields {/*swap-two-form-fields*/}
+### 交换两个表单字段 {/*swap-two-form-fields*/}
-This form lets you enter first and last name. It also has a checkbox controlling which field goes first. When you tick the checkbox, the "Last name" field will appear before the "First name" field.
+这个表单可以让你输入姓氏和名字。它还有一个复选框控制哪个字段放在前面。当你勾选复选框时,“姓氏”字段将出现在“名字”字段之前。
-It almost works, but there is a bug. If you fill in the "First name" input and tick the checkbox, the text will stay in the first input (which is now "Last name"). Fix it so that the input text *also* moves when you reverse the order.
+它几乎可以正常使用,但有一个 bug。如果你填写了“名字”输入框并勾选复选框,文本将保留在第一个输入框(也就是现在的“姓氏”)。修复它,使得输入框文本在你调换顺序时 *也* 会跟着移动。
-It seems like for these fields, their position within the parent is not enough. Is there some way to tell React how to match up the state between re-renders?
+似乎对于这两个字段来说,只知道它们在父组件中的位置并不足以实现功能。有没有办法告诉 React 如何匹配多次重新渲染中的 state?
@@ -1435,22 +1440,22 @@ export default function App() {
checked={reverse}
onChange={e => setReverse(e.target.checked)}
/>
- Reverse order
+ 调换顺序
);
if (reverse) {
return (
<>
-
-
+
+
{checkbox}
>
);
} else {
return (
<>
-
-
+
+
{checkbox}
>
);
@@ -1461,7 +1466,7 @@ function Field({ label }) {
const [text, setText] = useState('');
return (
);
if (reverse) {
return (
<>
-
-
+
+
{checkbox}
>
);
} else {
return (
<>
-
-
+
+
{checkbox}
>
);
@@ -1523,7 +1528,7 @@ function Field({ label }) {
const [text, setText] = useState('');
return (
{displayedContacts.map((contact, i) =>
@@ -2060,7 +2065,7 @@ export default function Contact({ contact }) {
>
);
@@ -2090,16 +2095,16 @@ button {
-The problem is that this example was using index as a `key`:
+问题在于这个例子使用了 index 作为 `key`:
```js
{displayedContacts.map((contact, i) =>
```
-However, you want the state to be associated with _each particular contact_.
+然而你应该让 state 与 _每个特定的联系人_ 相关联。
-Using the contact ID as a `key` instead fixes the issue:
+使用联系人的 ID 作为 `key` 就会修复这个问题:
@@ -2125,7 +2130,7 @@ export default function ContactList() {
setReverse(e.target.checked)
}}
/>{' '}
- Show in reverse order
+ 以相反的顺序显示
-State is associated with the tree position. A `key` lets you specify a named position instead of relying on order.
+state 与树中的位置相关联。 `key` 让你可以指定一个特定的位置,而不依赖于顺序。