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
You are probably here because you got the following error message:
7
+
Você provavelmente está aqui porque recebeu a seguinte mensagem de erro:
8
8
9
9
> Hooks can only be called inside the body of a function component.
10
10
11
-
There are three common reasons you might be seeing it:
11
+
Existem três razões comuns pelas quais você pode estar vendo a mensagem:
12
12
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.
13
+
1.Você pode ter**versões incompatíveis**do React e React DOM.
14
+
2.Você pode estar**quebrando as [Regras dos Hooks](/docs/hooks-rules.html)**.
15
+
3.Você pode ter**mais do que uma cópia do React**na mesma app.
16
16
17
-
Let's look at each of these cases.
17
+
Vamos olhar cada um destes casos.
18
18
19
-
## Mismatching Versions of React and React DOM {#mismatching-versions-of-react-and-react-dom}
19
+
## Versões incompatíveis do React e React DOM {#mismatching-versions-of-react-and-react-dom}
20
20
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).
21
+
Você pode estar usando uma versão do`react-dom` (< 16.8.0) ou`react-native` (< 0.59) que ainda não suporta _Hooks_. Você pode executar o script `npm ls react-dom`ou`npm ls react-native`na pasta da sua aplicação para verificar qual versão esta usando. Se você encontrar mais do que uma delas, isto talvez pode também causar problemas (mais detalhes sobre isso abaixo).
22
22
23
-
## Breaking the Rules of Hooks {#breaking-the-rules-of-hooks}
23
+
## Quebrando as Regras dos Hooks {#breaking-the-rules-of-hooks}
24
24
25
-
You can only call Hooks **while React is rendering a function component**:
25
+
Você pode somente chamar os _Hooks_**enquanto o React renderiza um componente funcional**:
26
26
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).
27
+
* ✅ Chame-os no nível superior do corpo de um componente funcional.
28
+
* ✅ Chame-os no nível superior do corpo de um [Hook customizado](/docs/hooks-custom.html).
29
29
30
-
**Learn more about this in the [Rules of Hooks](/docs/hooks-rules.html).**
30
+
**Aprenda mais sobre isto na [Regras dos Hooks](/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
+
// ✅ Bom: nível superior de um componente funcional
To avoid confusion, it’s **not**supported to call Hooks in other cases:
46
+
Para evitar confusão, **não**é suportado chamar Hooks em outros casos:
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
+
* 🔴 Não chame Hooks em componentes de classe.
49
+
* 🔴 Não chame em manipuladores de eventos.
50
+
* 🔴 Não chame Hooks dentro de funções passadas para `useMemo`, `useReducer`, ou`useEffect`.
51
51
52
-
If you break these rules, you might see this error.
52
+
Se você quebrar estas regras, poderá ver este erro.
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
+
// 🔴 Ruim: dentro de um manipulador de evento (para arrumar, mova-o para fora!)
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
+
// 🔴 Ruim: dentro do useMemo (para arrumar, mova-o para fora!)
66
66
const theme = useContext(ThemeContext);
67
67
return createStyle(theme);
68
68
});
@@ -71,52 +71,52 @@ function Bad2() {
71
71
72
72
class Bad3 extends React.Component {
73
73
render() {
74
-
// 🔴 Bad: inside a class component
74
+
// 🔴 Bad: dentro de um componente de classe
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
+
Você pode usar o [plugin `eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)para capturar alguns desses erros.
82
82
83
-
>Note
83
+
>Nota
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.
85
+
>[Hooks Customizados](/docs/hooks-custom.html)*podem* chamar outros Hooks (este é todo o seu propósito). Isso funciona porque Hooks customizados também devem ser chamados apenas enquanto um componente funcional estiver sendo renderizado.
86
86
87
87
88
-
## Duplicate React {#duplicate-react}
88
+
## React Duplicado {#duplicate-react}
89
89
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.
90
+
Para que os _Hooks_ funcionem, a importação do `react`no código da sua aplicação precisa ser resolvida no mesmo módulo que a importação do `react`de dentro do pacote do `react-dom`.
91
91
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.
92
+
Se estas importações do `react`resolverem para dois objetos exportados diferentes, você verá este alerta. Isso pode acontecer se você**acidentalmente acabar com duas cópias**do pacote`react`.
93
93
94
-
If you use Node for package management, you can run this check in your project folder:
94
+
Se você usa o gerenciador de pacotes do Node, você pode executar este verificador na pasta do seu projeto:
95
95
96
96
npm ls react
97
97
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.
98
+
Se você ver mais do que um React, você precisará descobrir porquê isso acontece e corrigir a sua árvore de dependências. Por exemplo, talvez uma biblioteca que você está usando incorretamente especifique o `react`como uma dependência (ao invés de uma dependência de pares). Até que essa biblioteca seja arrumada, [a resolução do Yarn](https://yarnpkg.com/lang/pt-br/docs/selective-version-resolutions/)é uma possível solução alternativa.
99
99
100
-
You can also try to debug this problem by adding some logs and restarting your development server:
100
+
Você pode tentar depurar este problema adicionando alguns logs e reiniciando seu servidor de desenvolvimento:
101
101
102
102
```js
103
-
//Add this in node_modules/react-dom/index.js
103
+
//Adicione isto no node_modules/react-dom/index.js
104
104
window.React1=require('react');
105
105
106
-
//Add this in your component file
106
+
//Adicione isto no arquivo do seu componente
107
107
require('react-dom');
108
108
window.React2=require('react');
109
109
console.log(window.React1===window.React2);
110
110
```
111
111
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.
112
+
Se ele imprimir`false`então você pode ter duas cópias do React e precisa descobrir porquê isso aconteceu. [Esta issue](https://github.com/facebook/react/issues/13991)inclue algumas razões comuns encontradas pela comunidade.
113
113
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.
114
+
Este problema pode também aparecer quando você usa `npm link`ou um equivalente. Neste caso, seu _bundler_ pode "ver" duas cópias do React — um na pasta da aplicação e outro na pasta da sua biblioteca. Assumindo que `myapp`e`mylib`são pastas irmãs, uma possível resolução é executar o script `npm link ../myapp/node_modules/react`de dentro da `mylib`. Isto fará com que a biblioteca use a cópia do React da aplicação.
115
115
116
-
>Note
116
+
>Nota
117
117
>
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.
118
+
>Em geral, o React suporta o uso de várias cópias independentes em uma página (por exemplo, se um aplicativo e um _widget_ de terceiros o usarem). Ele somente quebra se`require('react')`resolver diferentemente entre o componente e a cópia do `react-dom`que ele foi renderizado.
119
119
120
-
## Other Causes {#other-causes}
120
+
## Outros casos {#other-causes}
121
121
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.
122
+
Se nada disso funcionar, por favor comente [nesta issue](https://github.com/facebook/react/issues/13991)e nós iremos tentar ajudar. Tente criar um pequeno exemplo que reproduza o problema — você poderá descobrir o problema enquanto estiver fazendo isso.
0 commit comments