Skip to content

Commit b3975ee

Browse files
authored
Merge pull request #145 from reactjs/invalid-hook-call-warning
Translate "Invalid Hook Call Warning"
2 parents 69c7a4d + 4fde03a commit b3975ee

File tree

1 file changed

+42
-43
lines changed

1 file changed

+42
-43
lines changed
Lines changed: 42 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,68 @@
11
---
2-
title: Invalid Hook Call Warning
2+
title: "Предупреждение: некорректный вызов хука"
33
layout: single
44
permalink: warnings/invalid-hook-call-warning.html
55
---
66

7-
You are probably here because you got the following error message:
7+
Скорее всего, вы перешли на эту страницу, потому что получили следующее сообщение об ошибке:
88

99
> Hooks can only be called inside the body of a function component.
10+
11+
Есть три основные причины, по которым вы могли увидеть это предупреждение:
1012

11-
There are three common reasons you might be seeing it:
13+
1. **Несоответствие версий** React и React DOM.
14+
2. **Нарушение [правил хуков](/docs/hooks-rules.html)**.
15+
3. **Наличие более одной копии React** в одном приложении.
1216

13-
1. You might have **mismatching versions** of React and React DOM.
14-
2. You might be **breaking the [Rules of Hooks](/docs/hooks-rules.html)**.
15-
3. You might have **more than one copy of React** in the same app.
17+
Разберём каждый из этих случаев.
1618

17-
Let's look at each of these cases.
19+
## Несоответствие версий React и React DOM {#mismatching-versions-of-react-and-react-dom}
1820

19-
## Mismatching Versions of React and React DOM {#mismatching-versions-of-react-and-react-dom}
21+
Может быть, у вас установлена версия `react-dom` (< 16.8.0) или `react-native` (< 0.59), которая пока не поддерживает хуки. Вы можете выполнить `npm ls react-dom` или `npm ls react-native` в папке приложения, чтобы посмотреть, какую версию вы используете. Если у вас более одной версии, это также может привести к проблемам (подробнее об этом ниже).
2022

21-
You might be using a version of `react-dom` (< 16.8.0) or `react-native` (< 0.59) that doesn't yet support Hooks. You can run `npm ls react-dom` or `npm ls react-native` in your application folder to check which version you're using. If you find more than one of them, this might also create problems (more on that below).
23+
## Нарушение правил хуков {#breaking-the-rules-of-hooks}
2224

23-
## Breaking the Rules of Hooks {#breaking-the-rules-of-hooks}
25+
Вы можете вызывать хуки **только в то время, когда React рендерит функциональный компонент**:
2426

25-
You can only call Hooks **while React is rendering a function component**:
27+
* ✅ Вызывайте их на верхнем уровне в теле функционального компонента.
28+
* ✅ Вызывайте их на верхнем уровне в теле [пользовательского хука](/docs/hooks-custom.html).
2629

27-
* ✅ Call them at the top level in the body of a function component.
28-
* ✅ Call them at the top level in the body of a [custom Hook](/docs/hooks-custom.html).
29-
30-
**Learn more about this in the [Rules of Hooks](/docs/hooks-rules.html).**
30+
**Более подробно про это читайте на странице [Правила хуков](/docs/hooks-rules.html).**
3131

3232
```js{2-3,8-9}
3333
function Counter() {
34-
// ✅ Good: top-level in a function component
34+
// ✅ Хорошо: хук на вернем уровне функционального компонента
3535
const [count, setCount] = useState(0);
3636
// ...
3737
}
3838
3939
function useWindowWidth() {
40-
// ✅ Good: top-level in a custom Hook
40+
// ✅ Хорошо: хук на вернем уровне пользовательского хука
4141
const [width, setWidth] = useState(window.innerWidth);
4242
// ...
4343
}
4444
```
4545

46-
To avoid confusion, it’s **not** supported to call Hooks in other cases:
46+
Чтобы избежать путаницы, хуки **не** поддерживаются в некоторых случаях:
4747

48-
* 🔴 Do not call Hooks in class components.
49-
* 🔴 Do not call in event handlers.
50-
* 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or `useEffect`.
48+
* 🔴 Не вызывайте хуки в классовых компонентах.
49+
* 🔴 Не вызывайте их в обработчиках событий.
50+
* 🔴 Не вызывайте хуки внутри функций, переданных в `useMemo`, `useReducer` или `useEffect`.
5151

52-
If you break these rules, you might see this error.
52+
При нарушении перечисленных правил, можно столкнуться с этой ошибкой.
5353

5454
```js{3-4,11-12,20-21}
5555
function Bad1() {
5656
function handleClick() {
57-
// 🔴 Bad: inside an event handler (to fix, move it outside!)
57+
// 🔴 Плохо: внутри обработчика событий (для исправления переместите его на уровень выше!)
5858
const theme = useContext(ThemeContext);
5959
}
6060
// ...
6161
}
6262
6363
function Bad2() {
6464
const style = useMemo(() => {
65-
// 🔴 Bad: inside useMemo (to fix, move it outside!)
65+
// 🔴 Плохо: использование внутри useMemo (для исправления переместите его на уровень выше!)
6666
const theme = useContext(ThemeContext);
6767
return createStyle(theme);
6868
});
@@ -71,52 +71,51 @@ function Bad2() {
7171
7272
class Bad3 extends React.Component {
7373
render() {
74-
// 🔴 Bad: inside a class component
74+
// 🔴 Плохо: использование внутри классового компонента
7575
useEffect(() => {})
7676
// ...
7777
}
7878
}
7979
```
8080

81-
You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to catch some of these mistakes.
81+
Можно использовать [плагин `eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks), чтобы перехватить некоторые из указанных выше ошибок.
8282

83-
>Note
83+
>Примечание
8484
>
85-
>[Custom Hooks](/docs/hooks-custom.html) *may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering.
86-
85+
>[Пользовательские хуки](/docs/hooks-custom.html) *могут* вызывать другие хуки (именно в этом их суть). Это работает, как и ожидается, потому как пользовательские хуки также вызываются только во время рендеринга функционального компонента.
8786
88-
## Duplicate React {#duplicate-react}
87+
## Дублирование React {#duplicate-react}
8988

90-
In order for Hooks to work, the `react` import from your application code needs to resolve to the same module as the `react` import from inside the `react-dom` package.
89+
Для работы хуков необходимо, чтобы импорт `react` внутри приложения ссылался на тот же модуль, что и импорт внутри пакета `react-dom`.
9190

92-
If these `react` imports resolve to two different exports objects, you will see this warning. This may happen if you **accidentally end up with two copies** of the `react` package.
91+
Если эти `react` импорты ссылаются на два разных объекта экспорта, вы увидите такое предупреждение. Это произойдёт, если у вас случайно **оказалось несколько копий** пакета `react`
9392

94-
If you use Node for package management, you can run this check in your project folder:
93+
Если вы используете Node для управления пакетами, можете проверить копии пакета, находясь в папке проекта:
9594

9695
npm ls react
9796

98-
If you see more than one React, you'll need to figure out why this happens and fix your dependency tree. For example, maybe a library you're using incorrectly specifies `react` as a dependency (rather than a peer dependency). Until that library is fixed, [Yarn resolutions](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/) is one possible workaround.
97+
Если при выполнении этой команды выводится более одной версии React, нужно выяснить, почему подобное происходит, а потом исправить дерево зависимостей. Например, возможно, что библиотека, которую вы используете неправильно, указывает `react` в качестве зависимости (а не peer-зависимости). А пока эта библиотека не будет исправлена, [разрешения Yarn](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/) -- одно из возможных временных решений.
9998

100-
You can also try to debug this problem by adding some logs and restarting your development server:
99+
Вы также можете попробовать отладить эту проблему, добавив логирование и перезапустив сервер разработки:
101100

102101
```js
103-
// Add this in node_modules/react-dom/index.js
102+
// Добавьте это в файл node_modules/react-dom/index.js
104103
window.React1 = require('react');
105104

106-
// Add this in your component file
105+
// Добавьте это в ваш файл с компонентом
107106
require('react-dom');
108107
window.React2 = require('react');
109108
console.log(window.React1 === window.React2);
110109
```
111110

112-
If it prints `false` then you might have two Reacts and need to figure out why that happened. [This issue](https://github.com/facebook/react/issues/13991) includes some common reasons encountered by the community.
111+
Если код выше выводит `false`, то у вас может быть две версии React, а значит требуется выяснить, как это произошло. [Данное ишью](https://github.com/facebook/react/issues/13991) содержит некоторые распространённые причины, обнаруженные сообществом.
113112

114-
This problem can also come up when you use `npm link` or an equivalent. In that case, your bundler might "see" two Reacts — one in application folder and one in your library folder. Assuming `myapp` and `mylib` are sibling folders, one possible fix is to run `npm link ../myapp/node_modules/react` from `mylib`. This should make the library use the application's React copy.
113+
Эта проблема также может возникнуть при использовании команды `npm link` или ей подобной. В таком случае ваш бандлер может «увидеть» два пакета React -- один в папке приложения, а другой в папке вашей библиотеки. При условии, что `myapp` и `mylib` -- папки, находящиеся на одном уровне, выполнение `npm link ../myapp/node_modules/react` из-под папки `mylib` может помочь вам. Это должно заставить библиотеку использовать React-копию из приложения.
115114

116-
>Note
115+
>Примечание
117116
>
118-
>In general, React supports using multiple independent copies on one page (for example, if an app and a third-party widget both use it). It only breaks if `require('react')` resolves differently between the component and the `react-dom` copy it was rendered with.
117+
>В целом, React поддерживает использование нескольких независимых копий на одной странице (например, при одновременном использовании приложения и стороннего виджета). Корректная работа нарушается, если выражение `require('react')` разрешается по-разному между компонентом и копией из `react-dom`, с помощью которой он был отрендерен.
119118
120-
## Other Causes {#other-causes}
119+
## Другие случаи {#other-causes}
121120

122-
If none of this worked, please comment in [this issue](https://github.com/facebook/react/issues/13991) and we'll try to help. Try to create a small reproducing example — you might discover the problem as you're doing it.
121+
Если ни одно из решений не помогло, пожалуйста, оставьте комментарий в [этом ишью](https://github.com/facebook/react/issues/13991), после чего мы постараемся вам помочь. Попробуйте также создать небольшой пример, который воспроизводит вашу проблему.

0 commit comments

Comments
 (0)