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
* Tradução de Conteúdo opcional: Warnings
* Update src/content/warnings/invalid-aria-prop.md
Alterações solicitadas pelo @rick-ssa via PR.
Co-authored-by: Ricardo Santos da Silva <[email protected]>
* Update src/content/warnings/invalid-aria-prop.md
Alterações solicitadas pelo @rick-ssa via PR.
Co-authored-by: Ricardo Santos da Silva <[email protected]>
* Update src/content/warnings/invalid-hook-call-warning.md
Alterações solicitadas pelo @rick-ssa via PR.
Co-authored-by: Ricardo Santos da Silva <[email protected]>
* Update src/content/warnings/invalid-hook-call-warning.md
Alterações solicitadas pelo @rick-ssa via PR.
Co-authored-by: Ricardo Santos da Silva <[email protected]>
* Update src/content/warnings/invalid-hook-call-warning.md
Alterações solicitadas pelo @rick-ssa via PR.
Co-authored-by: Ricardo Santos da Silva <[email protected]>
* Modificaçoes solicitadas por @Zapotoczn
---------
Co-authored-by: Ricardo Santos da Silva <[email protected]>
This warning will fire if you attempt to render a DOM element with an`aria-*`prop that does not exist in the Web Accessibility Initiative (WAI) Accessible Rich Internet Application (ARIA) [specification](https://www.w3.org/TR/wai-aria-1.1/#states_and_properties).
5
+
Este aviso será disparado se você tentar renderizar um elemento DOM com uma propriedade`aria-*`que não existe na [especificação](https://www.w3.org/TR/wai-aria-1.1/#states_and_properties) da Web Accessibility Initiative (WAI) Accessible Rich Internet Application (ARIA).
6
6
7
-
1.If you feel that you are using a valid prop, check the spelling carefully. `aria-labelledby`and`aria-activedescendant`are often misspelled.
7
+
1.Se você acredita que está usando uma propriedade válida, verifique a ortografia cuidadosamente. `aria-labelledby`e`aria-activedescendant`são frequentemente escritas de forma incorreta.
8
8
9
-
2.If you wrote`aria-role`, you may have meant`role`.
3.Otherwise, if you're on the latest version of React DOM and verified that you're using a valid property name listed in the ARIA specification, please [report a bug](https://github.com/facebook/react/issues/new/choose).
11
+
3.Caso contrário, se você estiver na versão mais recente do React DOM e verificou que está usando um nome de propriedade válido listado na especificação ARIA, por favor, [relate um erro](https://github.com/facebook/react/issues/new/choose).
You are probably here because you got the following error message:
5
+
Provavelmente você está aqui porque recebeu a seguinte mensagem de erro:
6
6
7
7
<ConsoleBlocklevel="error">
8
8
9
-
Hooks can only be called inside the body of a function component.
9
+
Hooks só podem ser chamados dentro do corpo de um componente de função.
10
10
11
11
</ConsoleBlock>
12
12
13
-
There are three common reasons you might be seeing it:
13
+
Existem três razões comuns pelas quais você pode estar vendo isso:
14
14
15
-
1.You might be**breaking the Rules of Hooks**.
16
-
2.You might have**mismatching versions**of React and React DOM.
17
-
3.You might have**more than one copy of React**in the same app.
15
+
1.Você pode estar**quebrando as Regras dos Hooks**.
16
+
2.Você pode ter**versões incompatíveis**do React e do React DOM.
17
+
3.Você pode ter**mais de uma cópia do React**no mesmo aplicativo.
18
18
19
-
Let's look at each of these cases.
19
+
Vamos analisar cada um desses casos.
20
20
21
-
## Breaking Rules of Hooks {/*breaking-rules-of-hooks*/}
21
+
## Quebrando as Regras dos Hooks {/*breaking-rules-of-hooks*/}
22
22
23
-
Functions whose names start with`use`are called [*Hooks*](/reference/react)in React.
23
+
Funções cujos nomes começam com`use`são chamadas de [*Hooks*](/reference/react)no React.
24
24
25
-
**Don’t call Hooks inside loops, conditions, or nested functions.**Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component:
25
+
**Não chame Hooks dentro de loops, condições ou funções aninhadas.**Em vez disso, sempre use Hooks no nível superior da sua função de componente React, antes de qualquer retorno antecipado. Você só pode chamar Hooks enquanto o React está renderizando um componente de função:
26
26
27
-
* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component).
28
-
* ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks).
27
+
* ✅ Chame-os no nível superior no corpo de um [componente de função](/learn/your-first-component).
28
+
* ✅ Chame-os no nível superior no corpo de um [Hook personalizado](/learn/reusing-logic-with-custom-hooks).
29
29
30
30
```js{2-3,8-9}
31
31
function Counter() {
32
-
// ✅ Good: top-level in a function component
32
+
// ✅ Bom: no nível superior em um componente de função
33
33
const [count, setCount] = useState(0);
34
34
// ...
35
35
}
36
36
37
37
function useWindowWidth() {
38
-
// ✅ Good: top-level in a custom Hook
38
+
// ✅ Bom: no nível superior em um Hook personalizado
It’s **not**supported to call Hooks (functions starting with`use`) in any other cases, for example:
44
+
**Não**é suportado chamar Hooks (funções começando com`use`) em outros casos, por exemplo:
45
45
46
-
* 🔴 Do not call Hooks inside conditions or loops.
47
-
* 🔴 Do not call Hooks after a conditional `return`statement.
48
-
* 🔴 Do not call Hooks in event handlers.
49
-
* 🔴 Do not call Hooks in class components.
50
-
* 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or`useEffect`.
46
+
* 🔴 Não chame Hooks dentro de condições ou loops.
47
+
* 🔴 Não chame Hooks após uma instrução de `return`condicional.
48
+
* 🔴 Não chame Hooks em manipuladores de eventos.
49
+
* 🔴 Não chame Hooks em componentes de classe.
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 essas regras, poderá ver esse erro.
53
53
54
54
```js{3-4,11-12,20-21}
55
55
function Bad({ cond }) {
56
56
if (cond) {
57
-
// 🔴 Bad: inside a condition (to fix, move it outside!)
57
+
// 🔴 Ruim: dentro de uma condição (para corrigir, mova para fora!)
58
58
const theme = useContext(ThemeContext);
59
59
}
60
60
// ...
61
61
}
62
62
63
63
function Bad() {
64
64
for (let i = 0; i < 10; i++) {
65
-
// 🔴 Bad: inside a loop (to fix, move it outside!)
65
+
// 🔴 Ruim: dentro de um loop (para corrigir, mova para fora!)
66
66
const theme = useContext(ThemeContext);
67
67
}
68
68
// ...
@@ -72,22 +72,22 @@ function Bad({ cond }) {
72
72
if (cond) {
73
73
return;
74
74
}
75
-
// 🔴 Bad: after a conditional return (to fix, move it before the return!)
75
+
// 🔴 Ruim: após um retorno condicional (para corrigir, mova para antes do retorno!)
76
76
const theme = useContext(ThemeContext);
77
77
// ...
78
78
}
79
79
80
80
function Bad() {
81
81
function handleClick() {
82
-
// 🔴 Bad: inside an event handler (to fix, move it outside!)
82
+
// 🔴 Ruim: dentro de um manipulador de eventos (para corrigir, mova para fora!)
83
83
const theme = useContext(ThemeContext);
84
84
}
85
85
// ...
86
86
}
87
87
88
88
function Bad() {
89
89
const style = useMemo(() => {
90
-
// 🔴 Bad: inside useMemo (to fix, move it outside!)
90
+
// 🔴 Ruim: dentro de useMemo (para corrigir, mova para fora!)
91
91
const theme = useContext(ThemeContext);
92
92
return createStyle(theme);
93
93
});
@@ -96,63 +96,63 @@ function Bad() {
96
96
97
97
class Bad extends React.Component {
98
98
render() {
99
-
// 🔴 Bad: inside a class component (to fix, write a function component instead of a class!)
99
+
// 🔴 Ruim: dentro de um componente de classe (para corrigir, escreva um componente de função em vez de uma classe!)
100
100
useEffect(() => {})
101
101
// ...
102
102
}
103
103
}
104
104
```
105
105
106
-
You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks)to catch these mistakes.
106
+
Você pode usar o [plugin `eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)para detectar esses erros.
107
107
108
108
<Note>
109
109
110
-
[Custom Hooks](/learn/reusing-logic-with-custom-hooks)*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.
110
+
[Hooks personalizados](/learn/reusing-logic-with-custom-hooks)*podem* chamar outros Hooks (essa é a finalidade deles). Isso funciona porque Hooks personalizados também devem ser chamados apenas enquanto um componente de função está sendo renderizado.
111
111
112
112
</Note>
113
113
114
-
## Mismatching Versions of React and React DOM {/*mismatching-versions-of-react-and-react-dom*/}
114
+
## Versões Incompatíveis do React e React DOM {/*mismatching-versions-of-react-and-react-dom*/}
115
115
116
-
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).
116
+
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`npm ls react-dom`ou`npm ls react-native`na pasta do seu aplicativo para verificar qual versão está usando. Se encontrar mais de uma, isso também pode criar problemas (mais sobre isso abaixo).
117
117
118
-
## Duplicate React {/*duplicate-react*/}
118
+
## Cópia Duplicada do React {/*duplicate-react*/}
119
119
120
-
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.
120
+
Para que os Hooks funcionem, a importação de `react`no código da sua aplicação precisa ser resolvida para o mesmo módulo que a importação de `react`dentro do pacote `react-dom`.
121
121
122
-
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.
122
+
Se essas importações de `react`forem resolvidas para dois objetos de exportação diferentes, você verá este aviso. Isso pode acontecer se você**acidentalmente acabar com duas cópias**do pacote`react`.
123
123
124
-
If you use Node for package management, you can run this check in your project folder:
124
+
Se você usar Node para gerenciamento de pacotes, pode executar esta verificação na sua pasta de projeto:
125
125
126
126
<TerminalBlock>
127
127
128
128
npm ls react
129
129
130
130
</TerminalBlock>
131
131
132
-
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.
132
+
Se você ver mais de um React, precisará descobrir por que isso acontece e corrigir sua árvore de dependências. Por exemplo, talvez uma biblioteca que você está usando especifica incorretamente `react` como uma dependência (em vez de uma dependência peer). Até que essa biblioteca seja corrigida, [resoluções do Yarn](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/)são uma possível solução alternativa.
133
133
134
-
You can also try to debug this problem by adding some logs and restarting your development server:
134
+
Você também pode tentar depurar este problema adicionando alguns logs e reiniciando seu servidor de desenvolvimento:
135
135
136
136
```js
137
-
//Add this in node_modules/react-dom/index.js
137
+
//Adicione isso em node_modules/react-dom/index.js
138
138
window.React1=require('react');
139
139
140
-
//Add this in your component file
140
+
//Adicione isso no seu arquivo de componente
141
141
require('react-dom');
142
142
window.React2=require('react');
143
143
console.log(window.React1===window.React2);
144
144
```
145
145
146
-
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.
146
+
Se imprimir `false`então você pode ter dois Reacts e precisa descobrir por que isso aconteceu. [Este problema](https://github.com/facebook/react/issues/13991)inclui algumas razões comuns encontradas pela comunidade.
147
147
148
-
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.
148
+
Esse problema também pode ocorrer quando você usa `npm link`ou equivalente. Nesse caso, seu bundler pode "ver" dois Reacts — um na pasta da aplicação e outro na pasta da sua biblioteca. Supondo que `myapp`e`mylib`sejam pastas irmãs, uma possível correção é executar `npm link ../myapp/node_modules/react`a partir de `mylib`. Isso deve fazer com que a biblioteca use a cópia do React da aplicação.
149
149
150
150
<Note>
151
151
152
-
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.
152
+
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 usarem). Ele só quebra se`require('react')`for resolvido de maneira diferente entre o componente e a cópia do `react-dom`com a qual foi renderizado.
153
153
154
154
</Note>
155
155
156
-
## Other Causes {/*other-causes*/}
156
+
## Outras Causas {/*other-causes*/}
157
157
158
-
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.
158
+
Se nada disso funcionou, por favor comente neste [problema](https://github.com/facebook/react/issues/13991)e tentaremos ajudar. Tente criar um pequeno exemplo reproduzível — você pode descobrir o problema enquanto faz isso.
## Aviso do ReactDOMTestUtils.act() {/*reactdomtestutilsact-warning*/}
6
6
7
-
`act`from`react-dom/test-utils`has been deprecated in favor of`act`from`react`.
7
+
O `act`de`react-dom/test-utils`foi depreciado em favor do`act`do`react`.
8
8
9
-
Before:
9
+
Antes:
10
10
11
11
```js
12
12
import {act} from'react-dom/test-utils';
13
13
```
14
14
15
-
After:
15
+
Depois:
16
16
17
17
```js
18
18
import {act} from'react';
19
19
```
20
20
21
-
## Rest of ReactDOMTestUtils APIS {/*rest-of-reactdomtestutils-apis*/}
21
+
## Resto das APIs do ReactDOMTestUtils {/*rest-of-reactdomtestutils-apis*/}
22
22
23
-
All APIs except`act` have been removed.
23
+
Todas as APIs, exceto`act`, foram removidas.
24
24
25
-
The React Team recommends migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/)for a modern and well supported testing experience.
25
+
A equipe do React recomenda migrar seus testes para [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/)para uma experiência de teste moderna e bem suportada.
## Aviso do ReactTestRenderer.create() {/*reacttestrenderercreate-warning*/}
6
6
7
-
react-test-renderer is deprecated. A warning will fire whenever calling ReactTestRenderer.create() or ReactShallowRender.render(). The react-test-renderer package will remain available on NPM but will not be maintained and may break with new React features or changes to React's internals.
7
+
O react-test-renderer está descontinuado. Um aviso será emitido sempre que ReactTestRenderer.create() ou ReactShallowRender.render() forem chamados. O pacote react-test-renderer permanecerá disponível no NPM, mas não será mantido e pode quebrar com novos recursos do React ou mudanças nos internos do React.
8
8
9
-
The React Team recommends migrating your tests to [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/)or[@testing-library/react-native](https://callstack.github.io/react-native-testing-library/docs/getting-started)for a modern and well supported testing experience.
9
+
A equipe do React recomenda migrar seus testes para [@testing-library/react](https://testing-library.com/docs/react-testing-library/intro/)ou[@testing-library/react-native](https://callstack.github.io/react-native-testing-library/docs/getting-started)para uma experiência de teste moderna e bem suportada.
10
10
11
11
12
-
## new ShallowRenderer() warning {/*new-shallowrenderer-warning*/}
12
+
## Novo Aviso do ShallowRenderer() {/*new-shallowrenderer-warning*/}
13
13
14
-
The react-test-renderer package no longer exports a shallow renderer at`react-test-renderer/shallow`. This was simply a repackaging of a previously extracted separate package: `react-shallow-renderer`. Therefore you can continue using the shallow renderer in the same way by installing it directly. See[Github](https://github.com/enzymejs/react-shallow-renderer) / [NPM](https://www.npmjs.com/package/react-shallow-renderer).
14
+
O pacote react-test-renderer não exporta mais um shallow renderer em`react-test-renderer/shallow`. . Isto era simplesmente uma reembalagem de um pacote separado anteriormente extraído: `react-shallow-renderer`. Portanto, você pode continuar usando o shallow renderer da mesma maneira, instalando-o diretamente. Veja[Github](https://github.com/enzymejs/react-shallow-renderer) / [NPM](https://www.npmjs.com/package/react-shallow-renderer).
Most props on a JSX element are passed on to the component, however, there are two special props (`ref` and `key`) which are used by React, and are thus not forwarded to the component.
5
+
A maioria das props em um elemento JSX são passadas para o componente, no entanto, há duas props especiais (`ref` and `key`) que são usadas pelo React e, portanto, não são encaminhadas para o componente.
6
6
7
-
For instance, you can't read `props.key`from a component. If you need to access the same value within the child component, you should pass it as a different prop (ex: `<ListItemWrapper key={result.id} id={result.id} />`and read`props.id`). While this may seem redundant, it's important to separate app logic from hints to React.
7
+
Por exemplo, você não pode ler `props.key`de um componente. Se você precisar acessar o mesmo valor dentro do componente filho, deve passá-lo como uma prop diferente (ex: `<ListItemWrapper key={result.id} id={result.id} />`e ler`props.id`). Embora isso possa parecer redundante, é importante separar a lógica da aplicação das dicas para o React.
0 commit comments