You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
3.**Наличие более одной копии React** в одном приложении.
12
16
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
+
Разберём каждый из этих случаев.
16
18
17
-
Let's look at each of these cases.
19
+
## Несоответствие версий React и React DOM {#mismatching-versions-of-react-and-react-dom}
18
20
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` в папке приложения, чтобы посмотреть, какую версию вы используете. Если у вас более одной версии, это также может привести к проблемам (подробнее об этом ниже).
20
22
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}
22
24
23
-
## Breaking the Rules of Hooks {#breaking-the-rules-of-hooks}
25
+
Вы можете вызывать хуки **только в то время, когда React рендерит функциональный компонент**:
24
26
25
-
You can only call Hooks **while React is rendering a function component**:
27
+
* ✅ Вызывайте их на верхнем уровне в теле функционального компонента.
28
+
* ✅ Вызывайте их на верхнем уровне в теле [пользовательского хука](/docs/hooks-custom.html).
26
29
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).**
31
31
32
32
```js{2-3,8-9}
33
33
function Counter() {
34
-
// ✅ Good: top-level in a function component
34
+
// ✅ Хорошо: хук на вернем уровне функционального компонента
35
35
const [count, setCount] = useState(0);
36
36
// ...
37
37
}
38
38
39
39
function useWindowWidth() {
40
-
// ✅ Good: top-level in a custom Hook
40
+
// ✅ Хорошо: хук на вернем уровне пользовательского хука
To avoid confusion, it’s**not**supported to call Hooks in other cases:
46
+
Чтобы избежать путаницы, хуки**не**поддерживаются в некоторых случаях:
47
47
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`.
51
51
52
-
If you break these rules, you might see this error.
52
+
При нарушении перечисленных правил, можно столкнуться с этой ошибкой.
53
53
54
54
```js{3-4,11-12,20-21}
55
55
function Bad1() {
56
56
function handleClick() {
57
-
// 🔴 Bad: inside an event handler (to fix, move it outside!)
57
+
// 🔴 Плохо: внутри обработчика событий (для исправления переместите его на уровень выше!)
58
58
const theme = useContext(ThemeContext);
59
59
}
60
60
// ...
61
61
}
62
62
63
63
function Bad2() {
64
64
const style = useMemo(() => {
65
-
// 🔴 Bad: inside useMemo (to fix, move it outside!)
65
+
// 🔴 Плохо: использование внутри useMemo (для исправления переместите его на уровень выше!)
66
66
const theme = useContext(ThemeContext);
67
67
return createStyle(theme);
68
68
});
@@ -71,52 +71,51 @@ function Bad2() {
71
71
72
72
class Bad3 extends React.Component {
73
73
render() {
74
-
// 🔴 Bad: inside a class component
74
+
// 🔴 Плохо: использование внутри классового компонента
75
75
useEffect(() => {})
76
76
// ...
77
77
}
78
78
}
79
79
```
80
80
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), чтобы перехватить некоторые из указанных выше ошибок.
82
82
83
-
>Note
83
+
>Примечание
84
84
>
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)*могут* вызывать другие хуки (именно в этом их суть). Это работает, как и ожидается, потому как пользовательские хуки также вызываются только во время рендеринга функционального компонента.
87
86
88
-
## Duplicate React {#duplicate-react}
87
+
## Дублирование React {#duplicate-react}
89
88
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`.
91
90
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`
93
92
94
-
If you use Node for package management, you can run this check in your project folder:
93
+
Если вы используете Node для управления пакетами, можете проверить копии пакета, находясь в папке проекта:
95
94
96
95
npm ls react
97
96
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/)-- одно из возможных временных решений.
99
98
100
-
You can also try to debug this problem by adding some logs and restarting your development server:
99
+
Вы также можете попробовать отладить эту проблему, добавив логирование и перезапустив сервер разработки:
101
100
102
101
```js
103
-
//Add this in node_modules/react-dom/index.js
102
+
//Добавьте это в файл node_modules/react-dom/index.js
104
103
window.React1=require('react');
105
104
106
-
//Add this in your component file
105
+
//Добавьте это в ваш файл с компонентом
107
106
require('react-dom');
108
107
window.React2=require('react');
109
108
console.log(window.React1===window.React2);
110
109
```
111
110
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)содержит некоторые распространённые причины, обнаруженные сообществом.
113
112
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-копию из приложения.
115
114
116
-
>Note
115
+
>Примечание
117
116
>
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`, с помощью которой он был отрендерен.
119
118
120
-
## Other Causes {#other-causes}
119
+
## Другие случаи {#other-causes}
121
120
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