From 876dd947cc14186190c8530f85af18a1620faf61 Mon Sep 17 00:00:00 2001
From: "translate-react-bot[bot]"
<251169733+translate-react-bot[bot]@users.noreply.github.com>
Date: Thu, 14 May 2026 15:30:52 +0000
Subject: [PATCH 1/4] =?UTF-8?q?docs:=20translate=20`state-a-components-mem?=
=?UTF-8?q?ory.md`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../learn/state-a-components-memory.md | 979 +-----------------
1 file changed, 53 insertions(+), 926 deletions(-)
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 73d46bdab8..275de11ba6 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -1,25 +1,25 @@
---
-title: "State: A Component's Memory"
+title: "Состояние: память компонента"
---
-
+```html
-Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state*.
+Компоненты часто должны менять то, что отображается на экране, в результате взаимодействия. Ввод текста в форму должен обновлять поле ввода, нажатие «далее» в карусели изображений должно менять отображаемое изображение, нажатие «купить» должно помещать продукт в корзину. Компоненты должны «запоминать» вещи: текущее значение ввода, текущее изображение, корзину покупок. В React этот вид памяти, специфичный для компонента, называется *состоянием*.
-* How to add a state variable with the [`useState`](/reference/react/useState) Hook
-* What pair of values the `useState` Hook returns
-* How to add more than one state variable
-* Why state is called local
+* Как добавить переменную состояния с помощью хука [`useState`](/reference/react/useState)
+* Какую пару значений возвращает хук `useState`
+* Как добавить больше одной переменной состояния
+* Почему состояние называется локальным
-## When a regular variable isn’t enough {/*when-a-regular-variable-isnt-enough*/}
+## Когда обычной переменной недостаточно {/*when-a-regular-variable-isnt-enough*/}
-Here's a component that renders a sculpture image. Clicking the "Next" button should show the next sculpture by changing the `index` to `1`, then `2`, and so on. However, this **won't work** (you can try it!):
+Вот компонент, который отображает изображение скульптуры. Нажатие кнопки «Далее» должно показывать следующую скульптуру, изменяя `index` на `1`, затем `2` и так далее. Однако это **не сработает** (вы можете попробовать!).
@@ -151,46 +151,46 @@ button {
-The `handleClick` event handler is updating a local variable, `index`. But two things prevent that change from being visible:
+Обработчик события `handleClick` обновляет локальную переменную `index`. Но две вещи не позволяют этому изменению быть видимым:
-1. **Local variables don't persist between renders.** When React renders this component a second time, it renders it from scratch—it doesn't consider any changes to the local variables.
-2. **Changes to local variables won't trigger renders.** React doesn't realize it needs to render the component again with the new data.
+1. **Локальные переменные не сохраняются между рендерами.** Когда React повторно отрисовывает этот компонент, он отрисовывает его с нуля — он не учитывает какие-либо изменения локальных переменных.
+2. **Изменения локальных переменных не вызывают рендеринга.** React не понимает, что ему нужно снова отрисовать компонент с новыми данными.
-To update a component with new data, two things need to happen:
+Чтобы обновить компонент с новыми данными, необходимо, чтобы произошло две вещи:
-1. **Retain** the data between renders.
-2. **Trigger** React to render the component with new data (re-rendering).
+1. **Сохранить** данные между рендерами.
+2. **Запустить** React для отрисовки компонента с новыми данными (повторный рендеринг).
-The [`useState`](/reference/react/useState) Hook provides those two things:
+Хук [`useState`](/reference/react/useState) предоставляет эти две вещи:
-1. A **state variable** to retain the data between renders.
-2. A **state setter function** to update the variable and trigger React to render the component again.
+1. **Переменную состояния** для сохранения данных между рендерами.
+2. **Функцию установки состояния** для обновления переменной и запуска React для повторной отрисовки компонента.
-## Adding a state variable {/*adding-a-state-variable*/}
+## Добавление переменной состояния {/*adding-a-state-variable*/}
-To add a state variable, import `useState` from React at the top of the file:
+Чтобы добавить переменную состояния, импортируйте `useState` из React вверху файла:
```js
import { useState } from 'react';
```
-Then, replace this line:
+Затем замените эту строку:
```js
let index = 0;
```
-with
+на
```js
const [index, setIndex] = useState(0);
```
-`index` is a state variable and `setIndex` is the setter function.
+`index` — это переменная состояния, а `setIndex` — функция установки состояния.
-> The `[` and `]` syntax here is called [array destructuring](https://javascript.info/destructuring-assignment) and it lets you read values from an array. The array returned by `useState` always has exactly two items.
+> Синтаксис `[` и `]` здесь называется [деструктуризацией массива](https://javascript.info/destructuring-assignment), и он позволяет вам считывать значения из массива. Массив, возвращаемый `useState`, всегда имеет ровно два элемента.
-This is how they work together in `handleClick`:
+Вот как они работают вместе в `handleClick`:
```js
function handleClick() {
@@ -198,7 +198,7 @@ function handleClick() {
}
```
-Now clicking the "Next" button switches the current sculpture:
+Теперь нажатие кнопки «Далее» переключает текущую скульптуру:
@@ -331,57 +331,57 @@ button {
-### Meet your first Hook {/*meet-your-first-hook*/}
+### Знакомьтесь, ваш первый хук {/*meet-your-first-hook*/}
-In React, `useState`, as well as any other function starting with "`use`", is called a Hook.
+В React `useState`, а также любая другая функция, начинающаяся с «`use`», называется хуком.
-*Hooks* are special functions that are only available while React is [rendering](/learn/render-and-commit#step-1-trigger-a-render) (which we'll get into in more detail on the next page). They let you "hook into" different React features.
+*Хуки* — это специальные функции, которые доступны только во время [рендеринга](/learn/render-and-commit#step-1-trigger-a-render) React (о чем мы подробно расскажем на следующей странице). Они позволяют вам «подключаться» к различным функциям React.
-State is just one of those features, but you will meet the other Hooks later.
+Состояние — это всего лишь одна из этих функций, но с другими хуками вы познакомитесь позже.
-**Hooks—functions starting with `use`—can only be called at the top level of your components or [your own Hooks.](/learn/reusing-logic-with-custom-hooks)** You can't call Hooks inside conditions, loops, or other nested functions. Hooks are functions, but it's helpful to think of them as unconditional declarations about your component's needs. You "use" React features at the top of your component similar to how you "import" modules at the top of your file.
+**Хуки — функции, начинающиеся с `use` — можно вызывать только на верхнем уровне ваших компонентов или [ваших собственных хуков.](/learn/reusing-logic-with-custom-hooks)** Вы не можете вызывать хуки внутри условий, циклов или других вложенных функций. Хуки — это функции, но полезно думать о них как о безусловных объявлениях о потребностях вашего компонента. Вы «используете» функции React в верхней части вашего компонента, аналогично тому, как вы «импортируете» модули в верхней части вашего файла.
-### Anatomy of `useState` {/*anatomy-of-usestate*/}
+### Анатомия `useState` {/*anatomy-of-usestate*/}
-When you call [`useState`](/reference/react/useState), you are telling React that you want this component to remember something:
+Когда вы вызываете [`useState`](/reference/react/useState), вы сообщаете React, что хотите, чтобы этот компонент что-то запомнил:
```js
const [index, setIndex] = useState(0);
```
-In this case, you want React to remember `index`.
+В этом случае вы хотите, чтобы React запомнил `index`.
-The convention is to name this pair like `const [something, setSomething]`. You could name it anything you like, but conventions make things easier to understand across projects.
+Принято называть эту пару как `const [something, setSomething]`. Вы можете назвать ее как угодно, но соглашения упрощают понимание в разных проектах.
-The only argument to `useState` is the **initial value** of your state variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`.
+Единственным аргументом для `useState` является **начальное значение** вашей переменной состояния. В этом примере начальное значение `index` установлено в `0` с помощью `useState(0)`.
-Every time your component renders, `useState` gives you an array containing two values:
+Каждый раз, когда ваш компонент отрисовывается, `useState` предоставляет вам массив, содержащий два значения:
-1. The **state variable** (`index`) with the value you stored.
-2. The **state setter function** (`setIndex`) which can update the state variable and trigger React to render the component again.
+1. **Переменную состояния** (`index`) со значением, которое вы сохранили.
+2. **Функцию установки состояния** (`setIndex`), которая может обновить переменную состояния и запустить React для повторной отрисовки компонента.
-Here's how that happens in action:
+Вот как это происходит на практике:
```js
const [index, setIndex] = useState(0);
```
-1. **Your component renders the first time.** Because you passed `0` to `useState` as the initial value for `index`, it will return `[0, setIndex]`. React remembers `0` is the latest state value.
-2. **You update the state.** When a user clicks the button, it calls `setIndex(index + 1)`. `index` is `0`, so it's `setIndex(1)`. This tells React to remember `index` is `1` now and triggers another render.
-3. **Your component's second render.** React still sees `useState(0)`, but because React *remembers* that you set `index` to `1`, it returns `[1, setIndex]` instead.
-4. And so on!
+1. **Ваш компонент отрисовывается в первый раз.** Поскольку вы передали `0` в `useState` в качестве начального значения для `index`, он вернет `[0, setIndex]`. React помнит, что `0` — это последнее значение состояния.
+2. **Вы обновляете состояние.** Когда пользователь нажимает кнопку, она вызывает `setIndex(index + 1)`. `index` равен `0`, поэтому это `setIndex(1)`. Это сообщает React, что нужно запомнить, что `index` теперь равен `1`, и запускает другой рендеринг.
+3. **Второй рендеринг вашего компонента.** React по-прежнему видит `useState(0)`, но поскольку React *помнит*, что вы установили `index` равным `1`, он возвращает `[1, setIndex]` вместо этого.
+4. И так далее!
-## Giving a component multiple state variables {/*giving-a-component-multiple-state-variables*/}
+## Предоставление компоненту нескольких переменных состояния {/*giving-a-component-multiple-state-variables*/}
-You can have as many state variables of as many types as you like in one component. This component has two state variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details":
+У вас может быть столько переменных состояния любого типа, сколько вам нравится, в одном компоненте. Этот компонент имеет две переменные состояния: число `index` и логическое значение `showMore`, которое переключается при нажатии «Показать подробности»:
@@ -520,19 +520,19 @@ button {
-It is a good idea to have multiple state variables if their state is unrelated, like `index` and `showMore` in this example. But if you find that you often change two state variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it's more convenient to have a single state variable that holds an object than state variable per field. Read [Choosing the State Structure](/learn/choosing-the-state-structure) for more tips.
+Хорошей идеей является наличие нескольких переменных состояния, если их состояние не связано, как `index` и `showMore` в этом примере. Но если вы обнаружите, что часто изменяете две переменные состояния вместе, может быть проще объединить их в одну. Например, если у вас есть форма с множеством полей, удобнее иметь одну переменную состояния, которая содержит объект, чем переменную состояния для каждого поля. Прочтите [Выбор структуры состояния](/learn/choosing-the-state-structure) для получения дополнительных советов.
-#### How does React know which state to return? {/*how-does-react-know-which-state-to-return*/}
+#### Как React узнает, какое состояние возвращать? {/*how-does-react-know-which-state-to-return*/}
-You might have noticed that the `useState` call does not receive any information about *which* state variable it refers to. There is no "identifier" that is passed to `useState`, so how does it know which of the state variables to return? Does it rely on some magic like parsing your functions? The answer is no.
+Вы могли заметить, что вызов `useState` не получает никакой информации о *какой* переменной состояния он относится. Нет «идентификатора», который передается в `useState`, так как же он узнает, какую из переменных состояния вернуть? Полагается ли он на какую-то магию, например, на синтаксический анализ ваших функций? Ответ — нет.
-Instead, to enable their concise syntax, Hooks **rely on a stable call order on every render of the same component.** This works well in practice because if you follow the rule above ("only call Hooks at the top level"), Hooks will always be called in the same order. Additionally, a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) catches most mistakes.
+Вместо этого, чтобы включить их краткий синтаксис, хуки **основываются на стабильном порядке вызовов при каждом рендеринге одного и того же компонента.** Это хорошо работает на практике, потому что, если вы будете следовать правилу выше («вызывать хуки только на верхнем уровне»), хуки всегда будут вызываться в одном и том же порядке. Кроме того, [плагин линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) отлавливает большинство ошибок.
-Internally, React holds an array of state pairs for every component. It also maintains the current pair index, which is set to `0` before rendering. Each time you call `useState`, React gives you the next state pair and increments the index. You can read more about this mechanism in [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
+Внутри React хранит массив пар состояний для каждого компонента. Он также поддерживает текущий индекс пары, который устанавливается в `0` перед рендерингом. Каждый раз, когда вы вызываете `useState`, React предоставляет вам следующую пару состояний и увеличивает индекс. Вы можете прочитать больше об этом механизме в [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
-This example **doesn't use React** but it gives you an idea of how `useState` works internally:
+Этот пример **не использует React**, но он дает вам представление о том, как `useState` работает внутри:
@@ -635,877 +635,4 @@ let sculptureList = [{
artist: 'Eduardo Catalano',
description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
url: 'https://i.imgur.com/ZF6s192m.jpg',
- alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
-}, {
- name: 'Eternal Presence',
- artist: 'John Woodrow Wilson',
- description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
- url: 'https://i.imgur.com/aTtVpES.jpg',
- alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
-}, {
- name: 'Moai',
- artist: 'Unknown Artist',
- description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
- url: 'https://i.imgur.com/RCwLEoQm.jpg',
- alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
-}, {
- name: 'Blue Nana',
- artist: 'Niki de Saint Phalle',
- description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
- url: 'https://i.imgur.com/Sd1AgUOm.jpg',
- alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
-}, {
- name: 'Ultimate Form',
- artist: 'Barbara Hepworth',
- description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
- url: 'https://i.imgur.com/2heNQDcm.jpg',
- alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
-}, {
- name: 'Cavaliere',
- artist: 'Lamidi Olonade Fakeye',
- description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
- url: 'https://i.imgur.com/wIdGuZwm.png',
- alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
-}, {
- name: 'Big Bellies',
- artist: 'Alina Szapocznikow',
- description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
- url: 'https://i.imgur.com/AlHTAdDm.jpg',
- alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
-}, {
- name: 'Terracotta Army',
- artist: 'Unknown Artist',
- description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
- url: 'https://i.imgur.com/HMFmH6m.jpg',
- alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
-}, {
- name: 'Lunar Landscape',
- artist: 'Louise Nevelson',
- description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
- url: 'https://i.imgur.com/rN7hY6om.jpg',
- alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
-}, {
- name: 'Aureole',
- artist: 'Ranjani Shettar',
- description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
- url: 'https://i.imgur.com/okTpbHhm.jpg',
- alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
-}, {
- name: 'Hippos',
- artist: 'Taipei Zoo',
- description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
- url: 'https://i.imgur.com/6o5Vuyu.jpg',
- alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
-}];
-
-// Make UI match the initial state.
-updateDOM();
-```
-
-```html public/index.html
-
-
-
-
-
-
-
-```
-
-```css
-button { display: block; margin-bottom: 10px; }
-```
-
-
-
-You don't have to understand it to use React, but you might find this a helpful mental model.
-
-
-
-## State is isolated and private {/*state-is-isolated-and-private*/}
-
-State is local to a component instance on the screen. In other words, **if you render the same component twice, each copy will have completely isolated state!** Changing one of them will not affect the other.
-
-In this example, the `Gallery` component from earlier is rendered twice with no changes to its logic. Try clicking the buttons inside each of the galleries. Notice that their state is independent:
-
-
-
-```js
-import Gallery from './Gallery.js';
-
-export default function Page() {
- return (
-
}
-
-
- );
-}
-```
-
-```js src/data.js
-export const sculptureList = [{
- name: 'Homenaje a la Neurocirugía',
- artist: 'Marta Colvin Andrade',
- description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
- url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
-}, {
- name: 'Floralis Genérica',
- artist: 'Eduardo Catalano',
- description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
- url: 'https://i.imgur.com/ZF6s192m.jpg',
- alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
-}, {
- name: 'Eternal Presence',
- artist: 'John Woodrow Wilson',
- description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
- url: 'https://i.imgur.com/aTtVpES.jpg',
- alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
-}, {
- name: 'Moai',
- artist: 'Unknown Artist',
- description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
- url: 'https://i.imgur.com/RCwLEoQm.jpg',
- alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
-}, {
- name: 'Blue Nana',
- artist: 'Niki de Saint Phalle',
- description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
- url: 'https://i.imgur.com/Sd1AgUOm.jpg',
- alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
-}, {
- name: 'Ultimate Form',
- artist: 'Barbara Hepworth',
- description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
- url: 'https://i.imgur.com/2heNQDcm.jpg',
- alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
-}, {
- name: 'Cavaliere',
- artist: 'Lamidi Olonade Fakeye',
- description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
- url: 'https://i.imgur.com/wIdGuZwm.png',
- alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
-}, {
- name: 'Big Bellies',
- artist: 'Alina Szapocznikow',
- description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
- url: 'https://i.imgur.com/AlHTAdDm.jpg',
- alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
-}, {
- name: 'Terracotta Army',
- artist: 'Unknown Artist',
- description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
- url: 'https://i.imgur.com/HMFmH6m.jpg',
- alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
-}, {
- name: 'Lunar Landscape',
- artist: 'Louise Nevelson',
- description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
- url: 'https://i.imgur.com/rN7hY6om.jpg',
- alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
-}, {
- name: 'Aureole',
- artist: 'Ranjani Shettar',
- description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
- url: 'https://i.imgur.com/okTpbHhm.jpg',
- alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
-}, {
- name: 'Hippos',
- artist: 'Taipei Zoo',
- description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
- url: 'https://i.imgur.com/6o5Vuyu.jpg',
- alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
-}];
-```
-
-```css
-button { display: block; margin-bottom: 10px; }
-.Page > * {
- float: left;
- width: 50%;
- padding: 10px;
-}
-h2 { margin-top: 10px; margin-bottom: 0; }
-h3 {
- margin-top: 5px;
- font-weight: normal;
- font-size: 100%;
-}
-img { width: 120px; height: 120px; }
-button {
- display: block;
- margin-top: 10px;
- margin-bottom: 10px;
-}
-```
-
-
-
-This is what makes state different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it's "local" to the specific place on the screen. You rendered two `` components, so their state is stored separately.
-
-Also notice how the `Page` component doesn't "know" anything about the `Gallery` state or even whether it has any. Unlike props, **state is fully private to the component declaring it.** The parent component can't change it. This lets you add state to any component or remove it without impacting the rest of the components.
-
-What if you wanted both galleries to keep their states in sync? The right way to do it in React is to *remove* state from child components and add it to their closest shared parent. The next few pages will focus on organizing state of a single component, but we will return to this topic in [Sharing State Between Components.](/learn/sharing-state-between-components)
-
-
-
-* Use a state variable when a component needs to "remember" some information between renders.
-* State variables are declared by calling the `useState` Hook.
-* Hooks are special functions that start with `use`. They let you "hook into" React features like state.
-* Hooks might remind you of imports: they need to be called unconditionally. Calling Hooks, including `useState`, is only valid at the top level of a component or another Hook.
-* The `useState` Hook returns a pair of values: the current state and the function to update it.
-* You can have more than one state variable. Internally, React matches them up by their order.
-* State is private to the component. If you render it in two places, each copy gets its own state.
-
-
-
-
-
-
-
-#### Complete the gallery {/*complete-the-gallery*/}
-
-When you press "Next" on the last sculpture, the code crashes. Fix the logic to prevent the crash. You may do this by adding extra logic to event handler or by disabling the button when the action is not possible.
-
-After fixing the crash, add a "Previous" button that shows the previous sculpture. It shouldn't crash on the first sculpture.
-
-
-
-```js
-import { useState } from 'react';
-import { sculptureList } from './data.js';
-
-export default function Gallery() {
- const [index, setIndex] = useState(0);
- const [showMore, setShowMore] = useState(false);
-
- function handleNextClick() {
- setIndex(index + 1);
- }
-
- function handleMoreClick() {
- setShowMore(!showMore);
- }
-
- let sculpture = sculptureList[index];
- return (
- <>
-
-
- {sculpture.name}
- by {sculpture.artist}
-
-
- ({index + 1} of {sculptureList.length})
-
-
- {showMore &&
{sculpture.description}
}
-
- >
- );
-}
-```
-
-```js src/data.js
-export const sculptureList = [{
- name: 'Homenaje a la Neurocirugía',
- artist: 'Marta Colvin Andrade',
- description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
- url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
-}, {
- name: 'Floralis Genérica',
- artist: 'Eduardo Catalano',
- description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
- url: 'https://i.imgur.com/ZF6s192m.jpg',
- alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
-}, {
- name: 'Eternal Presence',
- artist: 'John Woodrow Wilson',
- description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
- url: 'https://i.imgur.com/aTtVpES.jpg',
- alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
-}, {
- name: 'Moai',
- artist: 'Unknown Artist',
- description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
- url: 'https://i.imgur.com/RCwLEoQm.jpg',
- alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
-}, {
- name: 'Blue Nana',
- artist: 'Niki de Saint Phalle',
- description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
- url: 'https://i.imgur.com/Sd1AgUOm.jpg',
- alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
-}, {
- name: 'Ultimate Form',
- artist: 'Barbara Hepworth',
- description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
- url: 'https://i.imgur.com/2heNQDcm.jpg',
- alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
-}, {
- name: 'Cavaliere',
- artist: 'Lamidi Olonade Fakeye',
- description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
- url: 'https://i.imgur.com/wIdGuZwm.png',
- alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
-}, {
- name: 'Big Bellies',
- artist: 'Alina Szapocznikow',
- description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
- url: 'https://i.imgur.com/AlHTAdDm.jpg',
- alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
-}, {
- name: 'Terracotta Army',
- artist: 'Unknown Artist',
- description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
- url: 'https://i.imgur.com/HMFmH6m.jpg',
- alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
-}, {
- name: 'Lunar Landscape',
- artist: 'Louise Nevelson',
- description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
- url: 'https://i.imgur.com/rN7hY6om.jpg',
- alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
-}, {
- name: 'Aureole',
- artist: 'Ranjani Shettar',
- description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
- url: 'https://i.imgur.com/okTpbHhm.jpg',
- alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
-}, {
- name: 'Hippos',
- artist: 'Taipei Zoo',
- description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
- url: 'https://i.imgur.com/6o5Vuyu.jpg',
- alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
-}];
-```
-
-```css
-button { display: block; margin-bottom: 10px; }
-.Page > * {
- float: left;
- width: 50%;
- padding: 10px;
-}
-h2 { margin-top: 10px; margin-bottom: 0; }
-h3 {
- margin-top: 5px;
- font-weight: normal;
- font-size: 100%;
-}
-img { width: 120px; height: 120px; }
-```
-
-
-
-
-
-This adds a guarding condition inside both event handlers and disables the buttons when needed:
-
-
-
-```js
-import { useState } from 'react';
-import { sculptureList } from './data.js';
-
-export default function Gallery() {
- const [index, setIndex] = useState(0);
- const [showMore, setShowMore] = useState(false);
-
- let hasPrev = index > 0;
- let hasNext = index < sculptureList.length - 1;
-
- function handlePrevClick() {
- if (hasPrev) {
- setIndex(index - 1);
- }
- }
-
- function handleNextClick() {
- if (hasNext) {
- setIndex(index + 1);
- }
- }
-
- function handleMoreClick() {
- setShowMore(!showMore);
- }
-
- let sculpture = sculptureList[index];
- return (
- <>
-
-
-
- {sculpture.name}
- by {sculpture.artist}
-
-
- ({index + 1} of {sculptureList.length})
-
-
- {showMore &&
{sculpture.description}
}
-
- >
- );
-}
-```
-
-```js src/data.js hidden
-export const sculptureList = [{
- name: 'Homenaje a la Neurocirugía',
- artist: 'Marta Colvin Andrade',
- description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
- url: 'https://i.imgur.com/Mx7dA2Y.jpg',
- alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
-}, {
- name: 'Floralis Genérica',
- artist: 'Eduardo Catalano',
- description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
- url: 'https://i.imgur.com/ZF6s192m.jpg',
- alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
-}, {
- name: 'Eternal Presence',
- artist: 'John Woodrow Wilson',
- description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
- url: 'https://i.imgur.com/aTtVpES.jpg',
- alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
-}, {
- name: 'Moai',
- artist: 'Unknown Artist',
- description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
- url: 'https://i.imgur.com/RCwLEoQm.jpg',
- alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
-}, {
- name: 'Blue Nana',
- artist: 'Niki de Saint Phalle',
- description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
- url: 'https://i.imgur.com/Sd1AgUOm.jpg',
- alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
-}, {
- name: 'Ultimate Form',
- artist: 'Barbara Hepworth',
- description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
- url: 'https://i.imgur.com/2heNQDcm.jpg',
- alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
-}, {
- name: 'Cavaliere',
- artist: 'Lamidi Olonade Fakeye',
- description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
- url: 'https://i.imgur.com/wIdGuZwm.png',
- alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
-}, {
- name: 'Big Bellies',
- artist: 'Alina Szapocznikow',
- description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
- url: 'https://i.imgur.com/AlHTAdDm.jpg',
- alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
-}, {
- name: 'Terracotta Army',
- artist: 'Unknown Artist',
- description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
- url: 'https://i.imgur.com/HMFmH6m.jpg',
- alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
-}, {
- name: 'Lunar Landscape',
- artist: 'Louise Nevelson',
- description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
- url: 'https://i.imgur.com/rN7hY6om.jpg',
- alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
-}, {
- name: 'Aureole',
- artist: 'Ranjani Shettar',
- description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
- url: 'https://i.imgur.com/okTpbHhm.jpg',
- alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
-}, {
- name: 'Hippos',
- artist: 'Taipei Zoo',
- description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
- url: 'https://i.imgur.com/6o5Vuyu.jpg',
- alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
-}];
-```
-
-```css
-button { display: block; margin-bottom: 10px; }
-.Page > * {
- float: left;
- width: 50%;
- padding: 10px;
-}
-h2 { margin-top: 10px; margin-bottom: 0; }
-h3 {
- margin-top: 5px;
- font-weight: normal;
- font-size: 100%;
-}
-img { width: 120px; height: 120px; }
-```
-
-
-
-Notice how `hasPrev` and `hasNext` are used *both* for the returned JSX and inside the event handlers! This handy pattern works because event handler functions ["close over"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) any variables declared while rendering.
-
-
-
-#### Fix stuck form inputs {/*fix-stuck-form-inputs*/}
-
-When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `` is set to always match the `firstName` variable, and the `value` for the second `` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using state variables instead.
-
-
-
-```js
-export default function Form() {
- let firstName = '';
- let lastName = '';
-
- function handleFirstNameChange(e) {
- firstName = e.target.value;
- }
-
- function handleLastNameChange(e) {
- lastName = e.target.value;
- }
-
- function handleReset() {
- firstName = '';
- lastName = '';
- }
-
- return (
-
- );
-}
-```
-
-```css
-h1 { margin-top: 10px; }
-```
-
-
-
-
-
-First, import `useState` from React. Then replace `firstName` and `lastName` with state variables declared by calling `useState`. Finally, replace every `firstName = ...` assignment with `setFirstName(...)`, and do the same for `lastName`. Don't forget to update `handleReset` too so that the reset button works.
-
-
-
-```js
-import { useState } from 'react';
-
-export default function Form() {
- const [firstName, setFirstName] = useState('');
- const [lastName, setLastName] = useState('');
-
- function handleFirstNameChange(e) {
- setFirstName(e.target.value);
- }
-
- function handleLastNameChange(e) {
- setLastName(e.target.value);
- }
-
- function handleReset() {
- setFirstName('');
- setLastName('');
- }
-
- return (
-
- );
-}
-```
-
-```css
-h1 { margin-top: 10px; }
-```
-
-
-
-
-
-#### Fix a crash {/*fix-a-crash*/}
-
-Here is a small form that is supposed to let the user leave some feedback. When the feedback is submitted, it's supposed to display a thank-you message. However, it crashes with an error message saying "Rendered fewer hooks than expected". Can you spot the mistake and fix it?
-
-
-
-Are there any limitations on _where_ Hooks may be called? Does this component break any rules? Check if there are any comments disabling the linter checks--this is where the bugs often hide!
-
-
-
-
-
-```js
-import { useState } from 'react';
-
-export default function FeedbackForm() {
- const [isSent, setIsSent] = useState(false);
- if (isSent) {
- return
Thank you!
;
- } else {
- // eslint-disable-next-line
- const [message, setMessage] = useState('');
- return (
-
- );
- }
-}
-```
-
-
-
-
-
-Hooks can only be called at the top level of the component function. Here, the first `isSent` definition follows this rule, but the `message` definition is nested in a condition.
-
-Move it out of the condition to fix the issue:
-
-
-
-```js
-import { useState } from 'react';
-
-export default function FeedbackForm() {
- const [isSent, setIsSent] = useState(false);
- const [message, setMessage] = useState('');
-
- if (isSent) {
- return
Thank you!
;
- } else {
- return (
-
- );
- }
-}
-```
-
-
-
-Remember, Hooks must be called unconditionally and always in the same order!
-
-You could also remove the unnecessary `else` branch to reduce the nesting. However, it's still important that all calls to Hooks happen *before* the first `return`.
-
-
-
-```js
-import { useState } from 'react';
-
-export default function FeedbackForm() {
- const [isSent, setIsSent] = useState(false);
- const [message, setMessage] = useState('');
-
- if (isSent) {
- return
Thank you!
;
- }
-
- return (
-
- );
-}
-```
-
-
-
-Try moving the second `useState` call after the `if` condition and notice how this breaks it again.
-
-If your linter is [configured for React](/learn/editor-setup#linting), you should see a lint error when you make a mistake like this. If you don't see an error when you try the faulty code locally, you need to set up linting for your project.
-
-
-
-#### Remove unnecessary state {/*remove-unnecessary-state*/}
-
-When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason the first time it shows "Hello, !", and then "Hello, [name]!" with the previous input every time after.
-
-To fix this code, remove the unnecessary state variable. (We will discuss about [why this didn't work](/learn/state-as-a-snapshot) later.)
-
-Can you explain why this state variable was unnecessary?
-
-
-
-```js
-import { useState } from 'react';
-
-export default function FeedbackForm() {
- const [name, setName] = useState('');
-
- function handleClick() {
- setName(prompt('What is your name?'));
- alert(`Hello, ${name}!`);
- }
-
- return (
-
- );
-}
-```
-
-
-
-
-
-Here is a fixed version that uses a regular `name` variable declared in the function that needs it:
-
-
-
-```js
-export default function FeedbackForm() {
- function handleClick() {
- const name = prompt('What is your name?');
- alert(`Hello, ${name}!`);
- }
-
- return (
-
- );
-}
-```
-
-
-
-A state variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don't introduce state variables when a regular variable works well.
-
-
-
-
+ alt:
\ No newline at end of file
From a7a2d1bd57c8a74924ea404cf2a252982fc18b68 Mon Sep 17 00:00:00 2001
From: "translate-react-bot[bot]"
<251169733+translate-react-bot[bot]@users.noreply.github.com>
Date: Mon, 18 May 2026 15:10:36 +0000
Subject: [PATCH 2/4] =?UTF-8?q?docs:=20translate=20`state-a-components-mem?=
=?UTF-8?q?ory.md`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../learn/state-a-components-memory.md | 986 +++++++++++++++++-
1 file changed, 929 insertions(+), 57 deletions(-)
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 275de11ba6..63cf3c7e88 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -1,10 +1,9 @@
---
-title: "Состояние: память компонента"
+title: "Состояние: Память компонента"
---
-```html
-Компоненты часто должны менять то, что отображается на экране, в результате взаимодействия. Ввод текста в форму должен обновлять поле ввода, нажатие «далее» в карусели изображений должно менять отображаемое изображение, нажатие «купить» должно помещать продукт в корзину. Компоненты должны «запоминать» вещи: текущее значение ввода, текущее изображение, корзину покупок. В React этот вид памяти, специфичный для компонента, называется *состоянием*.
+Компоненты часто должны изменять отображаемый контент в результате взаимодействия. Ввод текста в форму должен обновлять поле ввода, нажатие «Далее» в карусели изображений должно изменять отображаемое изображение, нажатие «Купить» должно добавлять товар в корзину. Компонентам нужно «помнить» вещи: текущее значение ввода, текущее изображение, содержимое корзины. В React такая специфичная для компонента память называется *состоянием* (state).
@@ -12,14 +11,14 @@ title: "Состояние: память компонента"
* Как добавить переменную состояния с помощью хука [`useState`](/reference/react/useState)
* Какую пару значений возвращает хук `useState`
-* Как добавить больше одной переменной состояния
+* Как добавить несколько переменных состояния
* Почему состояние называется локальным
## Когда обычной переменной недостаточно {/*when-a-regular-variable-isnt-enough*/}
-Вот компонент, который отображает изображение скульптуры. Нажатие кнопки «Далее» должно показывать следующую скульптуру, изменяя `index` на `1`, затем `2` и так далее. Однако это **не сработает** (вы можете попробовать!).
+Вот компонент, который отображает изображение скульптуры. Нажатие кнопки «Далее» должно показывать следующую скульптуру, изменяя `index` на `1`, затем на `2` и так далее. Однако это **не сработает** (можете попробовать!):
@@ -151,24 +150,24 @@ button {
-Обработчик события `handleClick` обновляет локальную переменную `index`. Но две вещи не позволяют этому изменению быть видимым:
+Обработчик события `handleClick` обновляет локальную переменную `index`. Но два фактора мешают увидеть это изменение:
-1. **Локальные переменные не сохраняются между рендерами.** Когда React повторно отрисовывает этот компонент, он отрисовывает его с нуля — он не учитывает какие-либо изменения локальных переменных.
-2. **Изменения локальных переменных не вызывают рендеринга.** React не понимает, что ему нужно снова отрисовать компонент с новыми данными.
+1. **Локальные переменные не сохраняются между рендерами.** Когда React повторно рендерит компонент, он делает это с нуля — изменения в локальных переменных не учитываются.
+2. **Изменения локальных переменных не вызывают рендер.** React не знает, что нужно снова отрендерить компонент с новыми данными.
-Чтобы обновить компонент с новыми данными, необходимо, чтобы произошло две вещи:
+Чтобы обновить компонент новыми данными, необходимо выполнить два условия:
1. **Сохранить** данные между рендерами.
-2. **Запустить** React для отрисовки компонента с новыми данными (повторный рендеринг).
+2. **Запустить** рендер компонента с новыми данными (повторный рендер).
-Хук [`useState`](/reference/react/useState) предоставляет эти две вещи:
+Хук [`useState`](/reference/react/useState) предоставляет оба этих механизма:
1. **Переменную состояния** для сохранения данных между рендерами.
-2. **Функцию установки состояния** для обновления переменной и запуска React для повторной отрисовки компонента.
+2. **Функцию установки состояния** для обновления переменной и запуска повторного рендера компонента.
## Добавление переменной состояния {/*adding-a-state-variable*/}
-Чтобы добавить переменную состояния, импортируйте `useState` из React вверху файла:
+Чтобы добавить переменную состояния, импортируйте `useState` из React в начале файла:
```js
import { useState } from 'react';
@@ -180,7 +179,7 @@ import { useState } from 'react';
let index = 0;
```
-на
+на:
```js
const [index, setIndex] = useState(0);
@@ -188,7 +187,7 @@ const [index, setIndex] = useState(0);
`index` — это переменная состояния, а `setIndex` — функция установки состояния.
-> Синтаксис `[` и `]` здесь называется [деструктуризацией массива](https://javascript.info/destructuring-assignment), и он позволяет вам считывать значения из массива. Массив, возвращаемый `useState`, всегда имеет ровно два элемента.
+> Синтаксис `[` и `]` здесь называется [деструктуризацией массива](https://javascript.info/destructuring-assignment) и позволяет извлекать значения из массива. Массив, возвращаемый `useState`, всегда содержит ровно два элемента.
Вот как они работают вместе в `handleClick`:
@@ -331,57 +330,57 @@ button {
-### Знакомьтесь, ваш первый хук {/*meet-your-first-hook*/}
+### Знакомство с первым хуком {/*meet-your-first-hook*/}
-В React `useState`, а также любая другая функция, начинающаяся с «`use`», называется хуком.
+В React `useState`, как и любая другая функция, начинающаяся с "`use`", называется хуком.
-*Хуки* — это специальные функции, которые доступны только во время [рендеринга](/learn/render-and-commit#step-1-trigger-a-render) React (о чем мы подробно расскажем на следующей странице). Они позволяют вам «подключаться» к различным функциям React.
+*Хуки* — это специальные функции, доступные только во время [рендера](/learn/render-and-commit#step-1-trigger-a-render) компонента (об этом подробнее на следующей странице). Они позволяют вам «подключаться» к различным возможностям React.
-Состояние — это всего лишь одна из этих функций, но с другими хуками вы познакомитесь позже.
+Состояние — лишь одна из таких возможностей, но с другими хуками вы познакомитесь позже.
-**Хуки — функции, начинающиеся с `use` — можно вызывать только на верхнем уровне ваших компонентов или [ваших собственных хуков.](/learn/reusing-logic-with-custom-hooks)** Вы не можете вызывать хуки внутри условий, циклов или других вложенных функций. Хуки — это функции, но полезно думать о них как о безусловных объявлениях о потребностях вашего компонента. Вы «используете» функции React в верхней части вашего компонента, аналогично тому, как вы «импортируете» модули в верхней части вашего файла.
+**Хуки — функции, начинающиеся с `use`, — можно вызывать только на верхнем уровне ваших компонентов или [в ваших собственных хуках.](/learn/reusing-logic-with-custom-hooks)** Вы не можете вызывать хуки внутри условий, циклов или других вложенных функций. Хуки — это функции, но полезно думать о них как о безусловных декларациях о потребностях вашего компонента. Вы «используете» возможности React в начале компонента так же, как «импортируете» модули в начале файла.
### Анатомия `useState` {/*anatomy-of-usestate*/}
-Когда вы вызываете [`useState`](/reference/react/useState), вы сообщаете React, что хотите, чтобы этот компонент что-то запомнил:
+Когда вы вызываете [`useState`](/reference/react/useState), вы говорите React, что хотите, чтобы этот компонент что-то запомнил:
```js
const [index, setIndex] = useState(0);
```
-В этом случае вы хотите, чтобы React запомнил `index`.
+В данном случае вы хотите, чтобы React запомнил `index`.
-Принято называть эту пару как `const [something, setSomething]`. Вы можете назвать ее как угодно, но соглашения упрощают понимание в разных проектах.
+По соглашению, эту пару называют `const [something, setSomething]`. Вы можете назвать её как угодно, но соглашения упрощают понимание кода в разных проектах.
-Единственным аргументом для `useState` является **начальное значение** вашей переменной состояния. В этом примере начальное значение `index` установлено в `0` с помощью `useState(0)`.
+Единственный аргумент `useState` — это **начальное значение** вашей переменной состояния. В этом примере начальное значение `index` устанавливается в `0` с помощью `useState(0)`.
-Каждый раз, когда ваш компонент отрисовывается, `useState` предоставляет вам массив, содержащий два значения:
+Каждый раз, когда ваш компонент рендерится, `useState` возвращает массив, содержащий два значения:
-1. **Переменную состояния** (`index`) со значением, которое вы сохранили.
-2. **Функцию установки состояния** (`setIndex`), которая может обновить переменную состояния и запустить React для повторной отрисовки компонента.
+1. **Переменная состояния** (`index`) с сохранённым значением.
+2. **Функция установки состояния** (`setIndex`), которая может обновить переменную состояния и запустить повторный рендер компонента.
-Вот как это происходит на практике:
+Вот как это происходит в действии:
```js
const [index, setIndex] = useState(0);
```
-1. **Ваш компонент отрисовывается в первый раз.** Поскольку вы передали `0` в `useState` в качестве начального значения для `index`, он вернет `[0, setIndex]`. React помнит, что `0` — это последнее значение состояния.
-2. **Вы обновляете состояние.** Когда пользователь нажимает кнопку, она вызывает `setIndex(index + 1)`. `index` равен `0`, поэтому это `setIndex(1)`. Это сообщает React, что нужно запомнить, что `index` теперь равен `1`, и запускает другой рендеринг.
-3. **Второй рендеринг вашего компонента.** React по-прежнему видит `useState(0)`, но поскольку React *помнит*, что вы установили `index` равным `1`, он возвращает `[1, setIndex]` вместо этого.
+1. **Ваш компонент рендерится в первый раз.** Поскольку вы передали `0` в `useState` в качестве начального значения для `index`, он вернёт `[0, setIndex]`. React запоминает, что `0` — это последнее значение состояния.
+2. **Вы обновляете состояние.** Когда пользователь нажимает кнопку, вызывается `setIndex(index + 1)`. `index` равен `0`, поэтому получается `setIndex(1)`. Это говорит React запомнить, что теперь `index` равен `1`, и запускает повторный рендер.
+3. **Второй рендер вашего компонента.** React по-прежнему видит `useState(0)`, но поскольку React *помнит*, что вы установили `index` в `1`, он возвращает `[1, setIndex]` вместо этого.
4. И так далее!
-## Предоставление компоненту нескольких переменных состояния {/*giving-a-component-multiple-state-variables*/}
+## Использование нескольких переменных состояния в компоненте {/*giving-a-component-multiple-state-variables*/}
-У вас может быть столько переменных состояния любого типа, сколько вам нравится, в одном компоненте. Этот компонент имеет две переменные состояния: число `index` и логическое значение `showMore`, которое переключается при нажатии «Показать подробности»:
+В одном компоненте может быть сколько угодно переменных состояния любого типа. Этот компонент имеет две переменные состояния: число `index` и булево значение `showMore`, которое переключается при нажатии на "Show details":
@@ -520,19 +519,19 @@ button {
-Хорошей идеей является наличие нескольких переменных состояния, если их состояние не связано, как `index` и `showMore` в этом примере. Но если вы обнаружите, что часто изменяете две переменные состояния вместе, может быть проще объединить их в одну. Например, если у вас есть форма с множеством полей, удобнее иметь одну переменную состояния, которая содержит объект, чем переменную состояния для каждого поля. Прочтите [Выбор структуры состояния](/learn/choosing-the-state-structure) для получения дополнительных советов.
+Иметь несколько переменных состояния имеет смысл, если они не связаны друг с другом, как `index` и `showMore` в этом примере. Но если вы обнаружите, что часто изменяете две переменные состояния одновременно, возможно, будет проще объединить их в одну. Например, если у вас есть форма с множеством полей, удобнее иметь одну переменную состояния, хранящую объект, чем по переменной состояния на каждое поле. Дополнительные советы см. в разделе [Выбор структуры состояния](/learn/choosing-the-state-structure).
-#### Как React узнает, какое состояние возвращать? {/*how-does-react-know-which-state-to-return*/}
+#### Как React узнает, какое состояние вернуть? {/*how-does-react-know-which-state-to-return*/}
-Вы могли заметить, что вызов `useState` не получает никакой информации о *какой* переменной состояния он относится. Нет «идентификатора», который передается в `useState`, так как же он узнает, какую из переменных состояния вернуть? Полагается ли он на какую-то магию, например, на синтаксический анализ ваших функций? Ответ — нет.
+Вы могли заметить, что вызов `useState` не получает никакой информации о том, к какой переменной состояния он относится. Нет "идентификатора", который передается в `useState`, так как же он узнает, какое из состояний вернуть? Полагается ли он на какую-то магию, например, парсинг ваших функций? Ответ — нет.
-Вместо этого, чтобы включить их краткий синтаксис, хуки **основываются на стабильном порядке вызовов при каждом рендеринге одного и того же компонента.** Это хорошо работает на практике, потому что, если вы будете следовать правилу выше («вызывать хуки только на верхнем уровне»), хуки всегда будут вызываться в одном и том же порядке. Кроме того, [плагин линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) отлавливает большинство ошибок.
+Вместо этого, чтобы обеспечить лаконичный синтаксис, хуки **полагаются на стабильный порядок вызовов при каждом рендеринге одного и того же компонента.** На практике это хорошо работает, потому что если вы следуете правилу выше ("вызывайте хуки только на верхнем уровне"), хуки всегда будут вызываться в одном и том же порядке. Кроме того, [плагин линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) улавливает большинство ошибок.
-Внутри React хранит массив пар состояний для каждого компонента. Он также поддерживает текущий индекс пары, который устанавливается в `0` перед рендерингом. Каждый раз, когда вы вызываете `useState`, React предоставляет вам следующую пару состояний и увеличивает индекс. Вы можете прочитать больше об этом механизме в [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
+Внутренне React хранит массив пар состояний для каждого компонента. Он также поддерживает текущий индекс пары, который устанавливается в `0` перед рендерингом. Каждый раз, когда вы вызываете `useState`, React предоставляет вам следующую пару состояний и увеличивает индекс. Вы можете прочитать больше об этом механизме в [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
-Этот пример **не использует React**, но он дает вам представление о том, как `useState` работает внутри:
+Этот пример **не использует React**, но дает представление о том, как `useState` работает внутри:
@@ -540,37 +539,37 @@ button {
let componentHooks = [];
let currentHookIndex = 0;
-// How useState works inside React (simplified).
+// Как useState работает внутри React (упрощенно).
function useState(initialState) {
let pair = componentHooks[currentHookIndex];
if (pair) {
- // This is not the first render,
- // so the state pair already exists.
- // Return it and prepare for next Hook call.
+ // Это не первый рендер,
+ // поэтому пара состояний уже существует.
+ // Возвращаем ее и готовимся к следующему вызову хука.
currentHookIndex++;
return pair;
}
- // This is the first time we're rendering,
- // so create a state pair and store it.
+ // Это первый рендер,
+ // поэтому создаем пару состояний и сохраняем ее.
pair = [initialState, setState];
function setState(nextState) {
- // When the user requests a state change,
- // put the new value into the pair.
+ // Когда пользователь запрашивает изменение состояния,
+ // помещаем новое значение в пару.
pair[0] = nextState;
updateDOM();
}
- // Store the pair for future renders
- // and prepare for the next Hook call.
+ // Сохраняем пару для будущих рендеров
+ // и готовимся к следующему вызову хука.
componentHooks[currentHookIndex] = pair;
currentHookIndex++;
return pair;
}
function Gallery() {
- // Each useState() call will get the next pair.
+ // Каждый вызов useState() получит следующую пару.
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
@@ -583,8 +582,8 @@ function Gallery() {
}
let sculpture = sculptureList[index];
- // This example doesn't use React, so
- // return an output object instead of JSX.
+ // Этот пример не использует React, поэтому
+ // возвращает объект вывода вместо JSX.
return {
onNextClick: handleNextClick,
onMoreClick: handleMoreClick,
@@ -598,13 +597,13 @@ function Gallery() {
}
function updateDOM() {
- // Reset the current Hook index
- // before rendering the component.
+ // Сбрасываем текущий индекс хука
+ // перед рендерингом компонента.
currentHookIndex = 0;
let output = Gallery();
- // Update the DOM to match the output.
- // This is the part React does for you.
+ // Обновляем DOM в соответствии с выводом.
+ // Это та часть, которую React делает для вас.
nextButton.onclick = output.onNextClick;
header.textContent = output.header;
moreButton.onclick = output.onMoreClick;
@@ -635,4 +634,877 @@ let sculptureList = [{
artist: 'Eduardo Catalano',
description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
url: 'https://i.imgur.com/ZF6s192m.jpg',
- alt:
\ No newline at end of file
+ alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
+}, {
+ name: 'Eternal Presence',
+ artist: 'John Woodrow Wilson',
+ description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
+ url: 'https://i.imgur.com/aTtVpES.jpg',
+ alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
+}, {
+ name: 'Moai',
+ artist: 'Unknown Artist',
+ description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
+ url: 'https://i.imgur.com/RCwLEoQm.jpg',
+ alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
+}, {
+ name: 'Blue Nana',
+ artist: 'Niki de Saint Phalle',
+ description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
+ url: 'https://i.imgur.com/Sd1AgUOm.jpg',
+ alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
+}, {
+ name: 'Ultimate Form',
+ artist: 'Barbara Hepworth',
+ description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
+ url: 'https://i.imgur.com/2heNQDcm.jpg',
+ alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
+}, {
+ name: 'Cavaliere',
+ artist: 'Lamidi Olonade Fakeye',
+ description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
+ url: 'https://i.imgur.com/wIdGuZwm.png',
+ alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
+}, {
+ name: 'Big Bellies',
+ artist: 'Alina Szapocznikow',
+ description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
+ url: 'https://i.imgur.com/AlHTAdDm.jpg',
+ alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
+}, {
+ name: 'Terracotta Army',
+ artist: 'Unknown Artist',
+ description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
+ url: 'https://i.imgur.com/HMFmH6m.jpg',
+ alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
+}, {
+ name: 'Lunar Landscape',
+ artist: 'Louise Nevelson',
+ description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
+ url: 'https://i.imgur.com/rN7hY6om.jpg',
+ alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
+}, {
+ name: 'Aureole',
+ artist: 'Ranjani Shettar',
+ description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
+ url: 'https://i.imgur.com/okTpbHhm.jpg',
+ alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
+}, {
+ name: 'Hippos',
+ artist: 'Taipei Zoo',
+ description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
+ url: 'https://i.imgur.com/6o5Vuyu.jpg',
+ alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
+}];
+
+// Обновляем UI в соответствии с начальным состоянием.
+updateDOM();
+```
+
+```html public/index.html
+
+
+
+
+
+
+
+```
+
+```css
+button { display: block; margin-bottom: 10px; }
+```
+
+
+
+Вам не обязательно понимать это, чтобы использовать React, но эта модель может быть полезной.
+
+
+
+## Состояние изолировано и приватно {/*state-is-isolated-and-private*/}
+
+Состояние локально для экземпляра компонента на экране. Другими словами, **если вы отрендерите один и тот же компонент дважды, каждая копия будет иметь полностью изолированное состояние!** Изменение одного из них не повлияет на другое.
+
+В этом примере компонент `Gallery` из предыдущего раздела рендерится дважды без изменений в его логике. Попробуйте нажать кнопки внутри каждой из галерей. Обратите внимание, что их состояния независимы:
+
+
+
+```js
+import Gallery from './Gallery.js';
+
+export default function Page() {
+ return (
+
}
+
+
+ );
+}
+```
+
+```js src/data.js
+export const sculptureList = [{
+ name: 'Homenaje a la Neurocirugía',
+ artist: 'Marta Colvin Andrade',
+ description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
+ url: 'https://i.imgur.com/Mx7dA2Y.jpg',
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+}, {
+ name: 'Floralis Genérica',
+ artist: 'Eduardo Catalano',
+ description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
+ url: 'https://i.imgur.com/ZF6s192m.jpg',
+ alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
+}, {
+ name: 'Eternal Presence',
+ artist: 'John Woodrow Wilson',
+ description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
+ url: 'https://i.imgur.com/aTtVpES.jpg',
+ alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
+}, {
+ name: 'Moai',
+ artist: 'Unknown Artist',
+ description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
+ url: 'https://i.imgur.com/RCwLEoQm.jpg',
+ alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
+}, {
+ name: 'Blue Nana',
+ artist: 'Niki de Saint Phalle',
+ description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
+ url: 'https://i.imgur.com/Sd1AgUOm.jpg',
+ alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
+}, {
+ name: 'Ultimate Form',
+ artist: 'Barbara Hepworth',
+ description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
+ url: 'https://i.imgur.com/2heNQDcm.jpg',
+ alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
+}, {
+ name: 'Cavaliere',
+ artist: 'Lamidi Olonade Fakeye',
+ description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
+ url: 'https://i.imgur.com/wIdGuZwm.png',
+ alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
+}, {
+ name: 'Big Bellies',
+ artist: 'Alina Szapocznikow',
+ description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
+ url: 'https://i.imgur.com/AlHTAdDm.jpg',
+ alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
+}, {
+ name: 'Terracotta Army',
+ artist: 'Unknown Artist',
+ description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
+ url: 'https://i.imgur.com/HMFmH6m.jpg',
+ alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
+}, {
+ name: 'Lunar Landscape',
+ artist: 'Louise Nevelson',
+ description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
+ url: 'https://i.imgur.com/rN7hY6om.jpg',
+ alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
+}, {
+ name: 'Aureole',
+ artist: 'Ranjani Shettar',
+ description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
+ url: 'https://i.imgur.com/okTpbHhm.jpg',
+ alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
+}, {
+ name: 'Hippos',
+ artist: 'Taipei Zoo',
+ description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
+ url: 'https://i.imgur.com/6o5Vuyu.jpg',
+ alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
+}];
+```
+
+```css
+button { display: block; margin-bottom: 10px; }
+.Page > * {
+ float: left;
+ width: 50%;
+ padding: 10px;
+}
+h2 { margin-top: 10px; margin-bottom: 0; }
+h3 {
+ margin-top: 5px;
+ font-weight: normal;
+ font-size: 100%;
+}
+img { width: 120px; height: 120px; }
+button {
+ display: block;
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+```
+
+
+
+Именно это отличает состояние от обычных переменных, которые вы можете объявить в начале модуля. Состояние не привязано к конкретному вызову функции или месту в коде, а "локально" для конкретного места на экране. Вы отрендерили два компонента ``, поэтому их состояния хранятся отдельно.
+
+Также обратите внимание, что компонент `Page` ничего не "знает" о состоянии `Gallery` или даже о том, есть ли оно у него. В отличие от пропсов, **состояние полностью приватно для компонента, который его объявляет.** Родительский компонент не может его изменить. Это позволяет добавлять или удалять состояние из любого компонента без влияния на остальные.
+
+Что, если вы захотите синхронизировать состояния обеих галерей? Правильный способ сделать это в React — *удалить* состояние из дочерних компонентов и добавить его к их ближайшему общему родителю. Следующие несколько страниц будут посвящены организации состояния одного компонента, но мы вернемся к этой теме в разделе [Обмен состоянием между компонентами.](/learn/sharing-state-between-components)
+
+
+
+* Используйте переменную состояния, когда компоненту нужно "запомнить" некоторую информацию между рендерами.
+* Переменные состояния объявляются вызовом хука `useState`.
+* Хуки — это специальные функции, которые начинаются с `use`. Они позволяют "подключиться" к функциям React, таким как состояние.
+* Хуки могут напомнить вам об импортах: их нужно вызывать безусловно. Вызовы хуков, включая `useState`, допустимы только на верхнем уровне компонента или другого хука.
+* Хук `useState` возвращает пару значений: текущее состояние и функцию для его обновления.
+* Вы можете иметь более одной переменной состояния. Внутренне React сопоставляет их по порядку.
+* Состояние приватно для компонента. Если вы рендерите его в двух местах, каждая копия получает свое собственное состояние.
+
+
+
+
+
+
+
+#### Завершите галерею {/*complete-the-gallery*/}
+
+При нажатии "Next" на последней скульптуре код выдает ошибку. Исправьте логику, чтобы предотвратить сбой. Вы можете сделать это, добавив дополнительную логику в обработчик событий или отключив кнопку, когда действие невозможно.
+
+После исправления сбоя добавьте кнопку "Previous", которая показывает предыдущую скульптуру. Она не должна выдавать ошибку на первой скульптуре.
+
+
+
+```js
+import { useState } from 'react';
+import { sculptureList } from './data.js';
+
+export default function Gallery() {
+ const [index, setIndex] = useState(0);
+ const [showMore, setShowMore] = useState(false);
+
+ function handleNextClick() {
+ setIndex(index + 1);
+ }
+
+ function handleMoreClick() {
+ setShowMore(!showMore);
+ }
+
+ let sculpture = sculptureList[index];
+ return (
+ <>
+
+
+ {sculpture.name}
+ by {sculpture.artist}
+
+
+ ({index + 1} of {sculptureList.length})
+
+
+ {showMore &&
{sculpture.description}
}
+
+ >
+ );
+}
+```
+
+```js src/data.js
+export const sculptureList = [{
+ name: 'Homenaje a la Neurocirugía',
+ artist: 'Marta Colvin Andrade',
+ description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
+ url: 'https://i.imgur.com/Mx7dA2Y.jpg',
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+}, {
+ name: 'Floralis Genérica',
+ artist: 'Eduardo Catalano',
+ description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
+ url: 'https://i.imgur.com/ZF6s192m.jpg',
+ alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
+}, {
+ name: 'Eternal Presence',
+ artist: 'John Woodrow Wilson',
+ description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
+ url: 'https://i.imgur.com/aTtVpES.jpg',
+ alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
+}, {
+ name: 'Moai',
+ artist: 'Unknown Artist',
+ description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
+ url: 'https://i.imgur.com/RCwLEoQm.jpg',
+ alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
+}, {
+ name: 'Blue Nana',
+ artist: 'Niki de Saint Phalle',
+ description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
+ url: 'https://i.imgur.com/Sd1AgUOm.jpg',
+ alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
+}, {
+ name: 'Ultimate Form',
+ artist: 'Barbara Hepworth',
+ description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
+ url: 'https://i.imgur.com/2heNQDcm.jpg',
+ alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
+}, {
+ name: 'Cavaliere',
+ artist: 'Lamidi Olonade Fakeye',
+ description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
+ url: 'https://i.imgur.com/wIdGuZwm.png',
+ alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
+}, {
+ name: 'Big Bellies',
+ artist: 'Alina Szapocznikow',
+ description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
+ url: 'https://i.imgur.com/AlHTAdDm.jpg',
+ alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
+}, {
+ name: 'Terracotta Army',
+ artist: 'Unknown Artist',
+ description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
+ url: 'https://i.imgur.com/HMFmH6m.jpg',
+ alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
+}, {
+ name: 'Lunar Landscape',
+ artist: 'Louise Nevelson',
+ description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
+ url: 'https://i.imgur.com/rN7hY6om.jpg',
+ alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
+}, {
+ name: 'Aureole',
+ artist: 'Ranjani Shettar',
+ description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
+ url: 'https://i.imgur.com/okTpbHhm.jpg',
+ alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
+}, {
+ name: 'Hippos',
+ artist: 'Taipei Zoo',
+ description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
+ url: 'https://i.imgur.com/6o5Vuyu.jpg',
+ alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
+}];
+```
+
+```css
+button { display: block; margin-bottom: 10px; }
+.Page > * {
+ float: left;
+ width: 50%;
+ padding: 10px;
+}
+h2 { margin-top: 10px; margin-bottom: 0; }
+h3 {
+ margin-top: 5px;
+ font-weight: normal;
+ font-size: 100%;
+}
+img { width: 120px; height: 120px; }
+```
+
+
+
+
+
+Здесь добавляется условие проверки в оба обработчика событий и отключаются кнопки, когда это необходимо:
+
+
+
+```js
+import { useState } from 'react';
+import { sculptureList } from './data.js';
+
+export default function Gallery() {
+ const [index, setIndex] = useState(0);
+ const [showMore, setShowMore] = useState(false);
+
+ let hasPrev = index > 0;
+ let hasNext = index < sculptureList.length - 1;
+
+ function handlePrevClick() {
+ if (hasPrev) {
+ setIndex(index - 1);
+ }
+ }
+
+ function handleNextClick() {
+ if (hasNext) {
+ setIndex(index + 1);
+ }
+ }
+
+ function handleMoreClick() {
+ setShowMore(!showMore);
+ }
+
+ let sculpture = sculptureList[index];
+ return (
+ <>
+
+
+
+ {sculpture.name}
+ by {sculpture.artist}
+
+
+ ({index + 1} of {sculptureList.length})
+
+
+ {showMore &&
{sculpture.description}
}
+
+ >
+ );
+}
+```
+
+```js src/data.js hidden
+export const sculptureList = [{
+ name: 'Homenaje a la Neurocirugía',
+ artist: 'Marta Colvin Andrade',
+ description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
+ url: 'https://i.imgur.com/Mx7dA2Y.jpg',
+ alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
+}, {
+ name: 'Floralis Genérica',
+ artist: 'Eduardo Catalano',
+ description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
+ url: 'https://i.imgur.com/ZF6s192m.jpg',
+ alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
+}, {
+ name: 'Eternal Presence',
+ artist: 'John Woodrow Wilson',
+ description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
+ url: 'https://i.imgur.com/aTtVpES.jpg',
+ alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
+}, {
+ name: 'Moai',
+ artist: 'Unknown Artist',
+ description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
+ url: 'https://i.imgur.com/RCwLEoQm.jpg',
+ alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
+}, {
+ name: 'Blue Nana',
+ artist: 'Niki de Saint Phalle',
+ description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
+ url: 'https://i.imgur.com/Sd1AgUOm.jpg',
+ alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
+}, {
+ name: 'Ultimate Form',
+ artist: 'Barbara Hepworth',
+ description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
+ url: 'https://i.imgur.com/2heNQDcm.jpg',
+ alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
+}, {
+ name: 'Cavaliere',
+ artist: 'Lamidi Olonade Fakeye',
+ description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
+ url: 'https://i.imgur.com/wIdGuZwm.png',
+ alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
+}, {
+ name: 'Big Bellies',
+ artist: 'Alina Szapocznikow',
+ description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
+ url: 'https://i.imgur.com/AlHTAdDm.jpg',
+ alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
+}, {
+ name: 'Terracotta Army',
+ artist: 'Unknown Artist',
+ description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
+ url: 'https://i.imgur.com/HMFmH6m.jpg',
+ alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
+}, {
+ name: 'Lunar Landscape',
+ artist: 'Louise Nevelson',
+ description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
+ url: 'https://i.imgur.com/rN7hY6om.jpg',
+ alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
+}, {
+ name: 'Aureole',
+ artist: 'Ranjani Shettar',
+ description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
+ url: 'https://i.imgur.com/okTpbHhm.jpg',
+ alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
+}, {
+ name: 'Hippos',
+ artist: 'Taipei Zoo',
+ description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
+ url: 'https://i.imgur.com/6o5Vuyu.jpg',
+ alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
+}];
+```
+
+```css
+button { display: block; margin-bottom: 10px; }
+.Page > * {
+ float: left;
+ width: 50%;
+ padding: 10px;
+}
+h2 { margin-top: 10px; margin-bottom: 0; }
+h3 {
+ margin-top: 5px;
+ font-weight: normal;
+ font-size: 100%;
+}
+img { width: 120px; height: 120px; }
+```
+
+
+
+Обратите внимание, что `hasPrev` и `hasNext` используются *как* для возвращаемого JSX, так и внутри обработчиков событий! Этот удобный шаблон работает, потому что функции обработчиков событий ["замыкают"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) любые переменные, объявленные во время рендеринга.
+
+
+
+#### Исправьте зависшие поля ввода формы {/*fix-stuck-form-inputs*/}
+
+Когда вы вводите текст в поля ввода, ничего не появляется. Как будто значения ввода "зависли" пустыми строками. `value` первого `` установлен так, чтобы всегда соответствовать переменной `firstName`, а `value` второго `` — чтобы всегда соответствовать переменной `lastName`. Это правильно. Оба поля ввода имеют обработчики событий `onChange`, которые пытаются обновить переменные на основе последнего ввода пользователя (`e.target.value`). Однако переменные, похоже, не "помнят" свои значения между повторными рендерами. Исправьте это, используя вместо них переменные состояния.
+
+
+
+```js
+export default function Form() {
+ let firstName = '';
+ let lastName = '';
+
+ function handleFirstNameChange(e) {
+ firstName = e.target.value;
+ }
+
+ function handleLastNameChange(e) {
+ lastName = e.target.value;
+ }
+
+ function handleReset() {
+ firstName = '';
+ lastName = '';
+ }
+
+ return (
+
+ );
+}
+```
+
+```css
+h1 { margin-top: 10px; }
+```
+
+
+
+
+
+Сначала импортируйте `useState` из React. Затем замените `firstName` и `lastName` переменными состояния, объявленными вызовом `useState`. Наконец, замените каждое присваивание `firstName = ...` на `setFirstName(...)`, и сделайте то же самое для `lastName`. Не забудьте также обновить `handleReset`, чтобы кнопка сброса работала.
+
+
+
+```js
+import { useState } from 'react';
+
+export default function Form() {
+ const [firstName, setFirstName] = useState('');
+ const [lastName, setLastName] = useState('');
+
+ function handleFirstNameChange(e) {
+ setFirstName(e.target.value);
+ }
+
+ function handleLastNameChange(e) {
+ setLastName(e.target.value);
+ }
+
+ function handleReset() {
+ setFirstName('');
+ setLastName('');
+ }
+
+ return (
+
+ );
+}
+```
+
+```css
+h1 { margin-top: 10px; }
+```
+
+
+
+
+
+#### Исправьте сбой {/*fix-a-crash*/}
+
+Вот небольшая форма, которая должна позволять пользователю оставлять отзывы. Когда отзыв отправлен, должно отображаться сообщение с благодарностью. Однако она выдает ошибку: «Rendered fewer hooks than expected». Можете ли вы найти ошибку и исправить её?
+
+
+
+Есть ли какие-либо ограничения на _то, где_ можно вызывать хуки? Нарушает ли этот компонент какие-либо правила? Проверьте, нет ли комментариев, отключающих проверки линтера — именно там часто скрываются ошибки!
+
+
+
+
+
+```js
+import { useState } from 'react';
+
+export default function FeedbackForm() {
+ const [isSent, setIsSent] = useState(false);
+ if (isSent) {
+ return
Thank you!
;
+ } else {
+ // eslint-disable-next-line
+ const [message, setMessage] = useState('');
+ return (
+
+ );
+ }
+}
+```
+
+
+
+
+
+Хуки можно вызывать только на верхнем уровне функции компонента. Здесь первое определение `isSent` следует этому правилу, но определение `message` вложено в условие.
+
+Переместите его из условия, чтобы исправить проблему:
+
+
+
+```js
+import { useState } from 'react';
+
+export default function FeedbackForm() {
+ const [isSent, setIsSent] = useState(false);
+ const [message, setMessage] = useState('');
+
+ if (isSent) {
+ return
Thank you!
;
+ } else {
+ return (
+
+ );
+ }
+}
+```
+
+
+
+Помните, что хуки должны вызываться безусловно и всегда в одном и том же порядке!
+
+Вы также можете удалить ненужную ветку `else`, чтобы уменьшить вложенность. Однако по-прежнему важно, чтобы все вызовы хуков происходили *перед* первым `return`.
+
+
+
+```js
+import { useState } from 'react';
+
+export default function FeedbackForm() {
+ const [isSent, setIsSent] = useState(false);
+ const [message, setMessage] = useState('');
+
+ if (isSent) {
+ return
Thank you!
;
+ }
+
+ return (
+
+ );
+}
+```
+
+
+
+Попробуйте переместить второй вызов `useState` после условия `if` и заметьте, как это снова сломает его.
+
+Если ваш линтер [настроен для React](/learn/editor-setup#linting), вы увидите ошибку линтера при совершении подобной ошибки. Если вы не видите ошибки при локальном тестировании некорректного кода, вам необходимо настроить линтинг для вашего проекта.
+
+
+
+#### Удалите ненужное состояние {/*remove-unnecessary-state*/}
+
+При нажатии на кнопку этот пример должен запрашивать имя пользователя, а затем отображать приветствующий алерт. Вы пытались использовать состояние для хранения имени, но по какой-то причине в первый раз отображается «Hello, !», а затем «Hello, [имя]!» с предыдущим вводом каждый раз после этого.
+
+Чтобы исправить этот код, удалите ненужную переменную состояния. (Мы обсудим [почему это не сработало](/learn/state-as-a-snapshot) позже.)
+
+Можете ли вы объяснить, почему эта переменная состояния была ненужной?
+
+
+
+```js
+import { useState } from 'react';
+
+export default function FeedbackForm() {
+ const [name, setName] = useState('');
+
+ function handleClick() {
+ setName(prompt('What is your name?'));
+ alert(`Hello, ${name}!`);
+ }
+
+ return (
+
+ );
+}
+```
+
+
+
+
+
+Вот исправленная версия, которая использует обычную переменную `name`, объявленную в функции, которая в ней нуждается:
+
+
+
+```js
+export default function FeedbackForm() {
+ function handleClick() {
+ const name = prompt('What is your name?');
+ alert(`Hello, ${name}!`);
+ }
+
+ return (
+
+ );
+}
+```
+
+
+
+Переменная состояния необходима только для хранения информации между повторными рендерами компонента. Внутри одного обработчика событий обычная переменная подойдет. Не вводите переменные состояния, когда обычная переменная работает хорошо.
+
+
+
+
\ No newline at end of file
From 84b2f3d42e37134e386e2830afde82fecc0e626b Mon Sep 17 00:00:00 2001
From: "translate-react-bot[bot]"
<251169733+translate-react-bot[bot]@users.noreply.github.com>
Date: Mon, 18 May 2026 16:19:19 +0000
Subject: [PATCH 3/4] =?UTF-8?q?docs:=20translate=20`state-a-components-mem?=
=?UTF-8?q?ory.md`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../learn/state-a-components-memory.md | 78 +++++++++----------
1 file changed, 39 insertions(+), 39 deletions(-)
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 63cf3c7e88..f7c96de49b 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -150,17 +150,17 @@ button {
-Обработчик события `handleClick` обновляет локальную переменную `index`. Но два фактора мешают увидеть это изменение:
+Обработчик события `handleClick` обновляет локальную переменную `index`. Но два фактора мешают этому изменению быть видимым:
-1. **Локальные переменные не сохраняются между рендерами.** Когда React повторно рендерит компонент, он делает это с нуля — изменения в локальных переменных не учитываются.
-2. **Изменения локальных переменных не вызывают рендер.** React не знает, что нужно снова отрендерить компонент с новыми данными.
+1. **Локальные переменные не сохраняются между рендерами.** Когда React повторно рендерит этот компонент, он делает это с нуля — изменения в локальных переменных не учитываются.
+2. **Изменения локальных переменных не вызывают рендер.** React не понимает, что нужно снова отрендерить компонент с новыми данными.
-Чтобы обновить компонент новыми данными, необходимо выполнить два условия:
+Чтобы обновить компонент новыми данными, должны произойти две вещи:
1. **Сохранить** данные между рендерами.
2. **Запустить** рендер компонента с новыми данными (повторный рендер).
-Хук [`useState`](/reference/react/useState) предоставляет оба этих механизма:
+Хук [`useState`](/reference/react/useState) предоставляет эти две возможности:
1. **Переменную состояния** для сохранения данных между рендерами.
2. **Функцию установки состояния** для обновления переменной и запуска повторного рендера компонента.
@@ -187,7 +187,7 @@ const [index, setIndex] = useState(0);
`index` — это переменная состояния, а `setIndex` — функция установки состояния.
-> Синтаксис `[` и `]` здесь называется [деструктуризацией массива](https://javascript.info/destructuring-assignment) и позволяет извлекать значения из массива. Массив, возвращаемый `useState`, всегда содержит ровно два элемента.
+> Синтаксис `[` и `]` здесь называется [деструктуризацией массива](https://javascript.info/destructuring-assignment) и позволяет считывать значения из массива. Массив, возвращаемый `useState`, всегда содержит ровно два элемента.
Вот как они работают вместе в `handleClick`:
@@ -334,13 +334,13 @@ button {
В React `useState`, как и любая другая функция, начинающаяся с "`use`", называется хуком.
-*Хуки* — это специальные функции, доступные только во время [рендера](/learn/render-and-commit#step-1-trigger-a-render) компонента (об этом подробнее на следующей странице). Они позволяют вам «подключаться» к различным возможностям React.
+*Хуки* — это специальные функции, доступные только во время [рендера](/learn/render-and-commit#step-1-trigger-a-render) компонента (об этом подробнее на следующей странице). Они позволяют вам «подключаться» к различным функциям React.
-Состояние — лишь одна из таких возможностей, но с другими хуками вы познакомитесь позже.
+Состояние — лишь одна из этих функций, но с другими хуками вы познакомитесь позже.
-**Хуки — функции, начинающиеся с `use`, — можно вызывать только на верхнем уровне ваших компонентов или [в ваших собственных хуках.](/learn/reusing-logic-with-custom-hooks)** Вы не можете вызывать хуки внутри условий, циклов или других вложенных функций. Хуки — это функции, но полезно думать о них как о безусловных декларациях о потребностях вашего компонента. Вы «используете» возможности React в начале компонента так же, как «импортируете» модули в начале файла.
+**Хуки — функции, начинающиеся с `use` — можно вызывать только на верхнем уровне ваших компонентов или [в ваших собственных хуках.](/learn/reusing-logic-with-custom-hooks)** Вы не можете вызывать хуки внутри условий, циклов или других вложенных функций. Хуки — это функции, но полезно думать о них как о безусловных декларациях о потребностях вашего компонента. Вы «используете» функции React в начале компонента так же, как «импортируете» модули в начале файла.
@@ -356,7 +356,7 @@ const [index, setIndex] = useState(0);
-По соглашению, эту пару называют `const [something, setSomething]`. Вы можете назвать её как угодно, но соглашения упрощают понимание кода в разных проектах.
+По соглашению, эта пара называется `const [something, setSomething]`. Вы можете назвать её как угодно, но соглашения упрощают понимание кода в разных проектах.
@@ -364,7 +364,7 @@ const [index, setIndex] = useState(0);
Каждый раз, когда ваш компонент рендерится, `useState` возвращает массив, содержащий два значения:
-1. **Переменная состояния** (`index`) с сохранённым значением.
+1. **Переменная состояния** (`index`) с сохраненным вами значением.
2. **Функция установки состояния** (`setIndex`), которая может обновить переменную состояния и запустить повторный рендер компонента.
Вот как это происходит в действии:
@@ -373,8 +373,8 @@ const [index, setIndex] = useState(0);
const [index, setIndex] = useState(0);
```
-1. **Ваш компонент рендерится в первый раз.** Поскольку вы передали `0` в `useState` в качестве начального значения для `index`, он вернёт `[0, setIndex]`. React запоминает, что `0` — это последнее значение состояния.
-2. **Вы обновляете состояние.** Когда пользователь нажимает кнопку, вызывается `setIndex(index + 1)`. `index` равен `0`, поэтому получается `setIndex(1)`. Это говорит React запомнить, что теперь `index` равен `1`, и запускает повторный рендер.
+1. **Ваш компонент рендерится в первый раз.** Поскольку вы передали `0` в `useState` в качестве начального значения для `index`, он вернет `[0, setIndex]`. React запоминает, что `0` — это последнее значение состояния.
+2. **Вы обновляете состояние.** Когда пользователь нажимает кнопку, вызывается `setIndex(index + 1)`. `index` равен `0`, поэтому получается `setIndex(1)`. Это говорит React запомнить, что `index` теперь равен `1`, и запускает повторный рендер.
3. **Второй рендер вашего компонента.** React по-прежнему видит `useState(0)`, но поскольку React *помнит*, что вы установили `index` в `1`, он возвращает `[1, setIndex]` вместо этого.
4. И так далее!
@@ -519,17 +519,17 @@ button {
-Иметь несколько переменных состояния имеет смысл, если они не связаны друг с другом, как `index` и `showMore` в этом примере. Но если вы обнаружите, что часто изменяете две переменные состояния одновременно, возможно, будет проще объединить их в одну. Например, если у вас есть форма с множеством полей, удобнее иметь одну переменную состояния, хранящую объект, чем по переменной состояния на каждое поле. Дополнительные советы см. в разделе [Выбор структуры состояния](/learn/choosing-the-state-structure).
+Иметь несколько переменных состояния — хорошая практика, если их состояние не связано друг с другом, как `index` и `showMore` в этом примере. Но если вы обнаружите, что часто изменяете две переменные состояния вместе, возможно, будет проще объединить их в одну. Например, если у вас есть форма с множеством полей, удобнее иметь одну переменную состояния, хранящую объект, чем по переменной состояния на каждое поле. Читайте [Выбор структуры состояния](/learn/choosing-the-state-structure) для получения дополнительных советов.
#### Как React узнает, какое состояние вернуть? {/*how-does-react-know-which-state-to-return*/}
-Вы могли заметить, что вызов `useState` не получает никакой информации о том, к какой переменной состояния он относится. Нет "идентификатора", который передается в `useState`, так как же он узнает, какое из состояний вернуть? Полагается ли он на какую-то магию, например, парсинг ваших функций? Ответ — нет.
+Вы могли заметить, что вызов `useState` не получает никакой информации о том, к какой переменной состояния он относится. Нет "идентификатора", который передается в `useState`, так как же он узнает, какое из состояний вернуть? Полагается ли он на какую-то магию, вроде парсинга ваших функций? Ответ — нет.
-Вместо этого, чтобы обеспечить лаконичный синтаксис, хуки **полагаются на стабильный порядок вызовов при каждом рендеринге одного и того же компонента.** На практике это хорошо работает, потому что если вы следуете правилу выше ("вызывайте хуки только на верхнем уровне"), хуки всегда будут вызываться в одном и том же порядке. Кроме того, [плагин линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) улавливает большинство ошибок.
+Вместо этого, чтобы обеспечить их лаконичный синтаксис, хуки **полагаются на стабильный порядок вызовов при каждом рендеринге одного и того же компонента.** На практике это хорошо работает, потому что если вы следуете правилу выше ("вызывайте хуки только на верхнем уровне"), хуки всегда будут вызываться в одном и том же порядке. Кроме того, [плагин линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) улавливает большинство ошибок.
-Внутренне React хранит массив пар состояний для каждого компонента. Он также поддерживает текущий индекс пары, который устанавливается в `0` перед рендерингом. Каждый раз, когда вы вызываете `useState`, React предоставляет вам следующую пару состояний и увеличивает индекс. Вы можете прочитать больше об этом механизме в [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
+Внутренне React хранит массив пар состояний для каждого компонента. Он также поддерживает текущий индекс пары, который устанавливается в `0` перед рендерингом. Каждый раз, когда вы вызываете `useState`, React предоставляет вам следующую пару состояний и увеличивает индекс. Вы можете прочитать больше об этом механизме в [React Hooks: Не магия, просто массивы.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
Этот пример **не использует React**, но дает представление о том, как `useState` работает внутри:
@@ -603,7 +603,7 @@ function updateDOM() {
let output = Gallery();
// Обновляем DOM в соответствии с выводом.
- // Это та часть, которую React делает для вас.
+ // Это та часть, которую React делает за вас.
nextButton.onclick = output.onNextClick;
header.textContent = output.header;
moreButton.onclick = output.onMoreClick;
@@ -729,9 +729,9 @@ button { display: block; margin-bottom: 10px; }
## Состояние изолировано и приватно {/*state-is-isolated-and-private*/}
-Состояние локально для экземпляра компонента на экране. Другими словами, **если вы отрендерите один и тот же компонент дважды, каждая копия будет иметь полностью изолированное состояние!** Изменение одного из них не повлияет на другое.
+Состояние является локальным для экземпляра компонента на экране. Другими словами, **если вы отобразите один и тот же компонент дважды, каждая копия будет иметь полностью изолированное состояние!** Изменение одного из них не повлияет на другое.
-В этом примере компонент `Gallery` из предыдущего раздела рендерится дважды без изменений в его логике. Попробуйте нажать кнопки внутри каждой из галерей. Обратите внимание, что их состояния независимы:
+В этом примере компонент `Gallery` из предыдущего раздела отображается дважды без каких-либо изменений в его логике. Попробуйте нажать кнопки внутри каждой из галерей. Обратите внимание, что их состояния независимы:
@@ -890,21 +890,21 @@ button {
-Именно это отличает состояние от обычных переменных, которые вы можете объявить в начале модуля. Состояние не привязано к конкретному вызову функции или месту в коде, а "локально" для конкретного места на экране. Вы отрендерили два компонента ``, поэтому их состояния хранятся отдельно.
+Именно это отличает состояние от обычных переменных, которые вы можете объявить в начале модуля. Состояние не привязано к конкретному вызову функции или месту в коде, а является "локальным" для конкретного места на экране. Вы отобразили два компонента ``, поэтому их состояние хранится отдельно.
-Также обратите внимание, что компонент `Page` ничего не "знает" о состоянии `Gallery` или даже о том, есть ли оно у него. В отличие от пропсов, **состояние полностью приватно для компонента, который его объявляет.** Родительский компонент не может его изменить. Это позволяет добавлять или удалять состояние из любого компонента без влияния на остальные.
+Также обратите внимание, что компонент `Page` "не знает" ничего о состоянии `Gallery` или даже о том, есть ли оно у него. В отличие от пропсов, **состояние полностью приватно для компонента, который его объявляет.** Родительский компонент не может его изменить. Это позволяет добавлять или удалять состояние из любого компонента без влияния на остальные.
-Что, если вы захотите синхронизировать состояния обеих галерей? Правильный способ сделать это в React — *удалить* состояние из дочерних компонентов и добавить его к их ближайшему общему родителю. Следующие несколько страниц будут посвящены организации состояния одного компонента, но мы вернемся к этой теме в разделе [Обмен состоянием между компонентами.](/learn/sharing-state-between-components)
+Что, если бы вы хотели, чтобы обе галереи синхронизировали свои состояния? Правильный способ сделать это в React — *удалить* состояние из дочерних компонентов и добавить его в их ближайший общий родительский компонент. Следующие несколько страниц будут посвящены организации состояния одного компонента, но мы вернемся к этой теме в разделе [Обмен состоянием между компонентами.](/learn/sharing-state-between-components)
-* Используйте переменную состояния, когда компоненту нужно "запомнить" некоторую информацию между рендерами.
+* Используйте переменную состояния, когда компоненту нужно "помнить" некоторую информацию между рендерами.
* Переменные состояния объявляются вызовом хука `useState`.
-* Хуки — это специальные функции, которые начинаются с `use`. Они позволяют "подключиться" к функциям React, таким как состояние.
-* Хуки могут напомнить вам об импортах: их нужно вызывать безусловно. Вызовы хуков, включая `useState`, допустимы только на верхнем уровне компонента или другого хука.
+* Хуки — это специальные функции, которые начинаются с `use`. Они позволяют "подключаться" к функциям React, таким как состояние.
+* Хуки могут напоминать импорты: их нужно вызывать безусловно. Вызовы хуков, включая `useState`, допустимы только на верхнем уровне компонента или другого хука.
* Хук `useState` возвращает пару значений: текущее состояние и функцию для его обновления.
* Вы можете иметь более одной переменной состояния. Внутренне React сопоставляет их по порядку.
-* Состояние приватно для компонента. Если вы рендерите его в двух местах, каждая копия получает свое собственное состояние.
+* Состояние приватно для компонента. Если вы отображаете его в двух местах, каждая копия получает свое собственное состояние.
@@ -916,7 +916,7 @@ button {
При нажатии "Next" на последней скульптуре код выдает ошибку. Исправьте логику, чтобы предотвратить сбой. Вы можете сделать это, добавив дополнительную логику в обработчик событий или отключив кнопку, когда действие невозможно.
-После исправления сбоя добавьте кнопку "Previous", которая показывает предыдущую скульптуру. Она не должна выдавать ошибку на первой скульптуре.
+После исправления сбоя добавьте кнопку "Previous", которая показывает предыдущую скульптуру. Она не должна вызывать сбой при первой скульптуре.
@@ -1058,7 +1058,7 @@ img { width: 120px; height: 120px; }
-Здесь добавляется условие проверки в оба обработчика событий и отключаются кнопки, когда это необходимо:
+Здесь добавлено условие защиты внутри обоих обработчиков событий, а кнопки отключаются при необходимости:
@@ -1224,7 +1224,7 @@ img { width: 120px; height: 120px; }
#### Исправьте зависшие поля ввода формы {/*fix-stuck-form-inputs*/}
-Когда вы вводите текст в поля ввода, ничего не появляется. Как будто значения ввода "зависли" пустыми строками. `value` первого `` установлен так, чтобы всегда соответствовать переменной `firstName`, а `value` второго `` — чтобы всегда соответствовать переменной `lastName`. Это правильно. Оба поля ввода имеют обработчики событий `onChange`, которые пытаются обновить переменные на основе последнего ввода пользователя (`e.target.value`). Однако переменные, похоже, не "помнят" свои значения между повторными рендерами. Исправьте это, используя вместо них переменные состояния.
+При вводе текста в поля ввода ничего не появляется. Похоже, значения полей ввода "зависли" на пустых строках. `value` первого `` установлено так, чтобы всегда соответствовать переменной `firstName`, а `value` второго `` — чтобы всегда соответствовать переменной `lastName`. Это правильно. Оба поля ввода имеют обработчики событий `onChange`, которые пытаются обновить переменные на основе последнего ввода пользователя (`e.target.value`). Однако переменные, похоже, не "помнят" свои значения между повторными рендерами. Исправьте это, используя вместо них переменные состояния.
@@ -1324,13 +1324,13 @@ h1 { margin-top: 10px; }
-#### Исправьте сбой {/*fix-a-crash*/}
+#### Исправление сбоя {/*fix-a-crash*/}
-Вот небольшая форма, которая должна позволять пользователю оставлять отзывы. Когда отзыв отправлен, должно отображаться сообщение с благодарностью. Однако она выдает ошибку: «Rendered fewer hooks than expected». Можете ли вы найти ошибку и исправить её?
+Вот небольшая форма, которая должна позволять пользователю оставлять отзывы. После отправки отзыва должно отображаться сообщение с благодарностью. Однако она выдает ошибку «Rendered fewer hooks than expected». Можете ли вы найти ошибку и исправить ее?
-Есть ли какие-либо ограничения на _то, где_ можно вызывать хуки? Нарушает ли этот компонент какие-либо правила? Проверьте, нет ли комментариев, отключающих проверки линтера — именно там часто скрываются ошибки!
+Существуют ли ограничения на _место_ вызова хуков? Нарушает ли этот компонент какие-либо правила? Проверьте, нет ли комментариев, отключающих проверки линтера — именно там часто скрываются ошибки!
@@ -1443,17 +1443,17 @@ export default function FeedbackForm() {
-Попробуйте переместить второй вызов `useState` после условия `if` и заметьте, как это снова сломает его.
+Попробуйте переместить второй вызов `useState` после условия `if` и заметьте, как это снова сломает код.
Если ваш линтер [настроен для React](/learn/editor-setup#linting), вы увидите ошибку линтера при совершении подобной ошибки. Если вы не видите ошибки при локальном тестировании некорректного кода, вам необходимо настроить линтинг для вашего проекта.
-#### Удалите ненужное состояние {/*remove-unnecessary-state*/}
+#### Удаление ненужного состояния {/*remove-unnecessary-state*/}
-При нажатии на кнопку этот пример должен запрашивать имя пользователя, а затем отображать приветствующий алерт. Вы пытались использовать состояние для хранения имени, но по какой-то причине в первый раз отображается «Hello, !», а затем «Hello, [имя]!» с предыдущим вводом каждый раз после этого.
+При нажатии на кнопку этот пример должен запрашивать имя пользователя, а затем отображать приветствие. Вы попытались использовать состояние для хранения имени, но по какой-то причине первый раз отображается «Hello, !», а затем «Hello, [имя]!» с предыдущим вводом каждый раз после этого.
-Чтобы исправить этот код, удалите ненужную переменную состояния. (Мы обсудим [почему это не сработало](/learn/state-as-a-snapshot) позже.)
+Чтобы исправить этот код, удалите ненужную переменную состояния. (Мы обсудим, [почему это не сработало](/learn/state-as-a-snapshot) позже.)
Можете ли вы объяснить, почему эта переменная состояния была ненужной?
@@ -1482,7 +1482,7 @@ export default function FeedbackForm() {
-Вот исправленная версия, которая использует обычную переменную `name`, объявленную в функции, которая в ней нуждается:
+Вот исправленная версия, использующая обычную переменную `name`, объявленную в функции, которая в ней нуждается:
@@ -1503,7 +1503,7 @@ export default function FeedbackForm() {
-Переменная состояния необходима только для хранения информации между повторными рендерами компонента. Внутри одного обработчика событий обычная переменная подойдет. Не вводите переменные состояния, когда обычная переменная работает хорошо.
+Переменная состояния необходима только для сохранения информации между повторными рендерами компонента. В пределах одного обработчика событий обычная переменная подойдет. Не вводите переменные состояния, когда хорошо работает обычная переменная.
From a69b6217ea4c817c93fd3fb45c74c1b9c016eab2 Mon Sep 17 00:00:00 2001
From: nivaldo
Date: Mon, 18 May 2026 14:28:00 -0300
Subject: [PATCH 4/4] chore: keep frontmatter title as-is
---
src/content/learn/state-a-components-memory.md | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index f7c96de49b..3793078830 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -1,6 +1,7 @@
---
-title: "Состояние: Память компонента"
+title: "State: A Component's Memory"
---
+
Компоненты часто должны изменять отображаемый контент в результате взаимодействия. Ввод текста в форму должен обновлять поле ввода, нажатие «Далее» в карусели изображений должно изменять отображаемое изображение, нажатие «Купить» должно добавлять товар в корзину. Компонентам нужно «помнить» вещи: текущее значение ввода, текущее изображение, содержимое корзины. В React такая специфичная для компонента память называется *состоянием* (state).
@@ -1507,4 +1508,4 @@ export default function FeedbackForm() {
-
\ No newline at end of file
+