Skip to content

Commit ea20319

Browse files
authored
Merge pull request #86 from airyboy/master
Rules of Hooks translation
2 parents bc72c29 + 085e5c6 commit ea20319

File tree

1 file changed

+45
-45
lines changed

1 file changed

+45
-45
lines changed

content/docs/hooks-rules.md

Lines changed: 45 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
---
22
id: hooks-rules
3-
title: Rules of Hooks
3+
title: Правила хуков
44
permalink: docs/hooks-rules.html
55
next: hooks-custom.html
66
prev: hooks-effect.html
77
---
88

9-
*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
9+
*Хуки* -- новинка в React 16.8, которая позволяет использовать состояние и другие возможности React без написания классов.
1010

11-
Hooks are JavaScript functions, but you need to follow two rules when using them. We provide a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to enforce these rules automatically:
11+
Хуки — обычные JavaScript-функции, но существует два правила, которым нужно следовать. Чтобы автоматически их применять мы создали [плагин для линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks):
1212

13-
### Only Call Hooks at the Top Level {#only-call-hooks-at-the-top-level}
13+
### Используйте хуки только на верхнем уровне {#only-call-hooks-at-the-top-level}
1414

15-
**Don't call Hooks inside loops, conditions, or nested functions.** Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple `useState` and `useEffect` calls. (If you're curious, we'll explain this in depth [below](#explanation).)
15+
**Не используйте хуки внутри циклов, условных операторов или вложенных функций** Вместо этого всегда используйте хуки только на верхнем уровне React-функций. Исполнение этого правила гарантирует, что хуки вызываются в одинаковой последовательности при каждом рендере компонента. Это позволит React правильно сохранять состояние хуков между множественными вызовами `useState` и `useEffect`. (Если вам интересно, подробное объяснение [ниже](#explanation).)
1616

17-
### Only Call Hooks from React Functions {#only-call-hooks-from-react-functions}
17+
### Вызывайте хуки только из React-функций {#only-call-hooks-from-react-functions}
1818

19-
**Don't call Hooks from regular JavaScript functions.** Instead, you can:
19+
**Не вызывайте хуки из обычных функций JavaScript.** Вместо этого можно:
2020

21-
*Call Hooks from React function components.
22-
*Call Hooks from custom Hooks (we'll learn about them [on the next page](/docs/hooks-custom.html)).
21+
*Вызывать хуки из функционального компонента React.
22+
*Вызывать хуки из пользовательского хука (мы научимся делать это [на следующей странице](/docs/hooks-custom.html)).
2323

24-
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
24+
Следуя этому правилу, можно гарантировать, что вся логика состояния компонента чётко видна из исходного кода.
2525

26-
## ESLint Plugin {#eslint-plugin}
26+
## Плагин для ESLint {#eslint-plugin}
2727

28-
We released an ESLint plugin called [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) that enforces these two rules. You can add this plugin to your project if you'd like to try it:
28+
Мы выпустили плагин для ESLint [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks), который принуждает к соблюдению этих двух правил. Если хотите испытать его в деле, добавьте этот плагин в ваш проект.
2929

3030
```bash
3131
npm install eslint-plugin-react-hooks
3232
```
3333

3434
```js
35-
// Your ESLint configuration
35+
// Конфигурация ESLint
3636
{
3737
"plugins": [
3838
// ...
@@ -45,28 +45,28 @@ npm install eslint-plugin-react-hooks
4545
}
4646
```
4747

48-
In the future, we intend to include this plugin by default into Create React App and similar toolkits.
48+
В будущем мы намереваемся включать этот плагин в Create React App и подобные инструменты по умолчанию.
4949

50-
**You can skip to the next page explaining how to write [your own Hooks](/docs/hooks-custom.html) now.** On this page, we'll continue by explaining the reasoning behind these rules.
50+
**Вы можете пропустить остаток этой страницы и перейти к созданию [собственного хука](/docs/hooks-custom.html).** Но если вам интересно, ниже приведено объяснение, почему правила хуков необходимы.
5151

52-
## Explanation {#explanation}
52+
## Объяснение {#explanation}
5353

54-
As we [learned earlier](/docs/hooks-state.html#tip-using-multiple-state-variables), we can use multiple State or Effect Hooks in a single component:
54+
Как мы [ранее узнали](/docs/hooks-state.html#tip-using-multiple-state-variables) хуки состояния или эффектов в одном и том же компоненте можно использовать многократно:
5555

5656
```js
5757
function Form() {
58-
// 1. Use the name state variable
58+
// 1. Используем переменную состояния name
5959
const [name, setName] = useState('Mary');
6060

61-
// 2. Use an effect for persisting the form
61+
// 2. Используем эффект для сохранения данных формы
6262
useEffect(function persistForm() {
6363
localStorage.setItem('formData', name);
6464
});
6565

66-
// 3. Use the surname state variable
66+
// 3. Используем переменную состояния surname
6767
const [surname, setSurname] = useState('Poppins');
6868

69-
// 4. Use an effect for updating the title
69+
// 4. Используем эффект для обновления заголовка страницы
7070
useEffect(function updateTitle() {
7171
document.title = name + ' ' + surname;
7272
});
@@ -75,63 +75,63 @@ function Form() {
7575
}
7676
```
7777

78-
So how does React know which state corresponds to which `useState` call? The answer is that **React relies on the order in which Hooks are called**. Our example works because the order of the Hook calls is the same on every render:
78+
Итак, как же React сопоставляет переменные состояния с вызовами `useState`? Ответ таков: **React полагается на порядок вызова хуков**. Наш пример работает, потому что порядок вызова хуков одинаков при каждом рендере.
7979

8080
```js
8181
// ------------
82-
// First render
82+
// Первый рендер
8383
// ------------
84-
useState('Mary') // 1. Initialize the name state variable with 'Mary'
85-
useEffect(persistForm) // 2. Add an effect for persisting the form
86-
useState('Poppins') // 3. Initialize the surname state variable with 'Poppins'
87-
useEffect(updateTitle) // 4. Add an effect for updating the title
84+
useState('Мэри') // 1. Инициализируем переменную name значением 'Mary'
85+
useEffect(persistForm) // 2. Добавляем эффект для сохранения данных формы
86+
useState('Поппинс') // 3. Инициализируем переменную surname значением 'Poppins'
87+
useEffect(updateTitle) // 4. Добавляем эффект для обновления заголовка страницы
8888

8989
// -------------
90-
// Second render
90+
// Второй рендер
9191
// -------------
92-
useState('Mary') // 1. Read the name state variable (argument is ignored)
93-
useEffect(persistForm) // 2. Replace the effect for persisting the form
94-
useState('Poppins') // 3. Read the surname state variable (argument is ignored)
95-
useEffect(updateTitle) // 4. Replace the effect for updating the title
92+
useState('Мэри') // 1. Читаем переменную состояния name (аргумент игнорируется)
93+
useEffect(persistForm) // 2. Заменяем эффект сохранения данных формы
94+
useState('Поппинс') // 3. Читаем переменную состояния surname (аргумент игнорируется)
95+
useEffect(updateTitle) // 4. Заменяем эффект обновления заголовка страницы
9696

9797
// ...
9898
```
9999

100-
As long as the order of the Hook calls is the same between renders, React can associate some local state with each of them. But what happens if we put a Hook call (for example, the `persistForm` effect) inside a condition?
100+
До тех пор пока порядок вызова хуков одинаков в каждом рендере, React может сопоставить некое внутреннее состояние с каждым из них. Но что случится, если мы поместим вызов хука (например, эффект `persistForm`) внутрь условного оператора?
101101

102102
```js
103-
// 🔴 We're breaking the first rule by using a Hook in a condition
103+
// 🔴 Нарушаем первое правило, помещая хук в условие
104104
if (name !== '') {
105105
useEffect(function persistForm() {
106106
localStorage.setItem('formData', name);
107107
});
108108
}
109109
```
110110

111-
The `name !== ''` condition is `true` on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition `false`. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
111+
Условие `name !== ''` равняется `true` при первом рендере, поэтому хук выполняется. Тем не менее, при следующем рендере пользователь может обратить это условие в `false`, очистив поля формы. Теперь во время рендера хук будет пропущен и порядок вызовов хуков изменится.
112112

113113
```js
114-
useState('Mary') // 1. Read the name state variable (argument is ignored)
115-
// useEffect(persistForm) // 🔴 This Hook was skipped!
116-
useState('Poppins') // 🔴 2 (but was 3). Fail to read the surname state variable
117-
useEffect(updateTitle) // 🔴 3 (but was 4). Fail to replace the effect
114+
useState('Mary') // 1. Читаем переменную состояния name (аргумент игнорируется)
115+
// useEffect(persistForm) // 🔴 Хук пропускается!
116+
useState('Poppins') // 🔴 2 (но ранее был 3). Ошибка при чтении переменной состояния surname
117+
useEffect(updateTitle) // 🔴 3 (но ранее был 4). Ошибка при замене эффекта
118118
```
119119

120-
React wouldn't know what to return for the second `useState` Hook call. React expected that the second Hook call in this component corresponds to the `persistForm` effect, just like during the previous render, but it doesn't anymore. From that point, every next Hook call after the one we skipped would also shift by one, leading to bugs.
120+
React не будет знать, что вернуть для второго вызова хука `useState`. React ожидал, что второй вызов хука в этом компоненте соответствует эффекту `persistForm`, так же как при предыдущем рендере, но это больше не так. Начиная с этого момента, вызов каждого хука, следующего за пропущенным, также будет сдвинут на один назад, что приведёт к ошибкам.
121121

122-
**This is why Hooks must be called on the top level of our components.** If we want to run an effect conditionally, we can put that condition *inside* our Hook:
122+
**Вот почему хуки должны вызываться на верхнем уровне компонента.** Если мы хотим запускать эффект по условию, то можем поместить это условие *внутрь* хука:
123123

124124
```js
125125
useEffect(function persistForm() {
126-
// 👍 We're not breaking the first rule anymore
126+
// 👍 Первое правило больше не нарушается
127127
if (name !== '') {
128128
localStorage.setItem('formData', name);
129129
}
130130
});
131131
```
132132

133-
**Note that you don't need to worry about this problem if you use the [provided lint rule](https://www.npmjs.com/package/eslint-plugin-react-hooks).** But now you also know *why* Hooks work this way, and which issues the rule is preventing.
133+
**Эта проблема не будет вас беспокоить, если вы включите в свой проект [наше правило линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks).** Но теперь вы знаете, *почему* хуки работают таким образом и какие проблемы это правило предотвращает.
134134

135-
## Next Steps {#next-steps}
135+
## Следующие шаги {#next-steps}
136136

137-
Finally, we're ready to learn about [writing your own Hooks](/docs/hooks-custom.html)! Custom Hooks let you combine Hooks provided by React into your own abstractions, and reuse common stateful logic between different components.
137+
Наконец-то мы готовы изучить как [написать свой собственный хук](/docs/hooks-custom.html)! Пользовательские хуки позволят вам включить собственные хуки React в ваши абстракции и повторно использовать общую логику состояния в различных компонентах.

0 commit comments

Comments
 (0)