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
Copy file name to clipboardExpand all lines: content/docs/hooks-state.md
+64-65Lines changed: 64 additions & 65 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,20 @@
1
1
---
2
2
id: hooks-state
3
-
title: Using the State Hook
3
+
title: Usando o State do Hook
4
4
permalink: docs/hooks-state.html
5
5
next: hooks-effect.html
6
6
prev: hooks-overview.html
7
7
---
8
8
9
-
*Hooks*are a new addition in React 16.8. They let you use state and other React features without writing a class.
9
+
*Hooks*são a nova adição ao React 16.8. Eles permitem que você use o state e outras funcionalidades do React sem precisar escrever classes.
10
10
11
-
The [previous page](/docs/hooks-intro.html)introduced Hooks with this example:
11
+
A [página anterior](/docs/hooks-intro.html)introduziu Hooks com o seguinte exemplo:
12
12
13
13
```js{4-5}
14
14
import React, { useState } from 'react';
15
15
16
16
function Example() {
17
-
// Declare a new state variable, which we'll call "count"
17
+
// Declarar uma nova variável de state, na qual chamaremos de "count"
18
18
const [count, setCount] = useState(0);
19
19
20
20
return (
@@ -28,11 +28,11 @@ function Example() {
28
28
}
29
29
```
30
30
31
-
We'll start learning about Hooks by comparing this code to an equivalent class example.
31
+
Vamos começar aprendendo sobre Hooks comparando este código com um exemplo equivalente a classe.
32
32
33
-
## Equivalent Class Example {#equivalent-class-example}
33
+
## Exemplo equivalente a Classe {#equivalent-class-example}
34
34
35
-
If you used classes in React before, this code should look familiar:
35
+
Se você já usou classes no React, este código deve parecer familiar:
36
36
37
37
```js
38
38
classExampleextendsReact.Component {
@@ -56,39 +56,39 @@ class Example extends React.Component {
56
56
}
57
57
```
58
58
59
-
The state starts as`{ count: 0 }`, and we increment`state.count`when the user clicks a button by calling `this.setState()`. We'll use snippets from this class throughout the page.
59
+
O state começa como`{ count: 0 }`, e aumentamos o`state.count`chamando `this.setState()` quando o usuário clica o botão. Vamos utilizar trechos dessa classe ao longo da página.
60
60
61
-
>Note
61
+
>Nota
62
62
>
63
-
>You might be wondering why we're using a counter here instead of a more realistic example. This is to help us focus on the API while we're still making our first steps with Hooks.
63
+
>Você pode estar se perguntando porque estamos usando um *counter* aqui ao invés de um exemplo mais realista. Isto é pra nos ajudar a focar na API enquanto ainda damos os primeiros passos com Hooks.
64
64
65
-
## Hooks and Function Components {#hooks-and-function-components}
65
+
## Hooks e Componentes de Função {#hooks-and-function-components}
66
66
67
-
As a reminder, function components in React look like this:
67
+
Para lembrar, componentes de função, no React, parecem com isto:
68
68
69
69
```js
70
70
constExample= (props) => {
71
-
//You can use Hooks here!
71
+
//Você pode usar Hooks aqui!
72
72
return<div />;
73
73
}
74
74
```
75
75
76
-
or this:
76
+
ou isto:
77
77
78
78
```js
79
79
functionExample(props) {
80
-
//You can use Hooks here!
80
+
//Você pode usar Hooks aqui!
81
81
return<div />;
82
82
}
83
83
```
84
84
85
-
You might have previously known these as "stateless components". We're now introducing the ability to use React state from these, so we prefer the name "function components".
85
+
Você pode ter conhecido estes exemplos como "componentes sem estado". Nós estamos introduzindo a habilidade de utilizar o state do React neles, portanto preferimos o nome "componente de função".
86
86
87
-
Hooks **don't**work inside classes. But you can use them instead of writing classes.
87
+
Hooks **não**funcionam dentro de classes. Mas você pode usá-los ao invés de escrever classes.
88
88
89
-
## What's a Hook? {#whats-a-hook}
89
+
## O que é um Hook? {#whats-a-hook}
90
90
91
-
Our new example starts by importing the `useState` Hook from React:
91
+
Nosso novo exemplo começa importando o `useState` Hook do React:
92
92
93
93
```js{1}
94
94
import React, { useState } from 'react';
@@ -98,17 +98,17 @@ function Example() {
98
98
}
99
99
```
100
100
101
-
**What is a Hook?**A Hook is a special function that lets you "hook into" React features. For example, `useState`is a Hook that lets you add React state to function components. We'll learn other Hooks later.
101
+
**O que é um Hook?**Um Hook é uma função especial que te permitem utilizar recursos do React. Por exemplo, `useState`é um Hook que te permite adicionar o state do React a um componente de função. Vamos aprender outros Hooks mais tarde.
102
102
103
-
**When would I use a Hook?**If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We're going to do that right now!
103
+
**Quando eu deveria usar um Hook?**Se você escreve um componente de função e percebe que precisa adicionar algum state para ele, anteriormente você tinha que converte-lo para uma classe. Agora você pode usar um Hook dentro de um componente de função existente. Vamos fazer isso agora mesmo!
104
104
105
-
>Note:
105
+
>Nota:
106
106
>
107
-
>There are some special rules about where you can and can't use Hooks within a component. We'll learn them in [Rules of Hooks](/docs/hooks-rules.html).
107
+
>Existem algumas regras especiais sobre onde você pode ou não utilizar Hooks dentro de um componente. Vamos aprender elas em [Regras dos Hooks](/docs/hooks-rules.html).
108
108
109
-
## Declaring a State Variable {#declaring-a-state-variable}
109
+
## Declarando uma variável State {#declaring-a-state-variable}
110
110
111
-
In a class, we initialize the`count`state to `0`by setting `this.state`to`{ count: 0 }`in the constructor:
111
+
Em uma classe, inicializamos o state`count`para `0`definindo `this.state`para`{ count: 0 }`no construtor:
112
112
113
113
```js{4-6}
114
114
class Example extends React.Component {
@@ -120,76 +120,75 @@ class Example extends React.Component {
120
120
}
121
121
```
122
122
123
-
In a function component, we have no `this`, so we can't assign or read`this.state`. Instead, we call the`useState`Hook directly inside our component:
123
+
Em um componente de função, não temos `this`, portanto não podemos definir ou ler`this.state`. Em vez disso, chamamos o Hook`useState`dentro do nosso component:
124
124
125
125
```js{4,5}
126
126
import React, { useState } from 'react';
127
127
128
128
function Example() {
129
-
// Declare a new state variable, which we'll call "count"
129
+
// Declarar uma nova variável de state, na qual chamaremos de "count"
130
130
const [count, setCount] = useState(0);
131
131
```
132
132
133
-
**What does calling`useState`do?**It declares a "state variable". Our variable is called `count`but we could call it anything else, like`banana`. This is a way to "preserve" some values between the function calls — `useState`is a new way to use the exact same capabilities that`this.state`provides in a class. Normally, variables "disappear" when the function exits but state variables are preserved by React.
133
+
**O que o`useState`faz?**Ele declara um variável state. Nossa variável é chamada de `count`mas poderiamos chamar de qualquer coisa, como`banana`. Esta é uma maneira de "preservar" alguns valores entre as chamadas de funções — `useState`é uma nova maneira de usar as mesmas capacidades que o`this.state`tem em uma classe. Normalmente, variáveis "desaparecem" quando a função sai mas variáveis de state são preservadas pelo React.
134
134
135
-
**What do we pass to`useState`as an argument?**The only argument to the `useState()`Hook is the initial state. Unlike with classes, the state doesn't have to be an object. We can keep a number or a string if that's all we need. In our example, we just want a number for how many times the user clicked, so pass `0` as initial state for our variable. (If we wanted to store two different values in state, we would call `useState()`twice.)
135
+
**O que passamos para o`useState`como argumento?**O único argumento para useState() do Hook é o state inicial. Diferente de classes, o state não tem que ser um objeto. Podemos manter um número ou uma string se for tudo que precisamos. No nosso exemplo, apenas queremos um número para quantas vezes o usuário clicou, então passamos 0 como state inicial para nossa variável. (Se quiséssemos guardar dois valores diferentes no state, chamariamos `useState()`duas vezes.)
136
136
137
-
**What does`useState`return?**It returns a pair of values: the current state and a function that updates it. This is why we write`const [count, setCount] = useState()`. This is similar to`this.state.count`and`this.setState`in a class, except you get them in a pair. If you're not familiar with the syntax we used, we'll come back to it [at the bottom of this page](/docs/hooks-state.html#tip-what-do-square-brackets-mean).
137
+
**O que`useState`retorna?**Ele retorna um par de valores: o state atual e uma função que atualiza o state. É por isto que escrevemos`const [count, setCount] = useState()`. Isto é similar ao`this.state.count`e`this.setState`em uma classe, exceto o fato de pegá-los em par. Se você não está familiarizado com a sintaxe que usamos, vamos voltar nisso [no final dessa página](/docs/hooks-state.html#tip-what-do-square-brackets-mean).
138
138
139
-
Now that we know what the`useState` Hook does, our example should make more sense:
139
+
Agora que sabemos o que o`useState`do Hook faz, nosso exemplo deve fazer mais sentido:
140
140
141
141
```js{4,5}
142
142
import React, { useState } from 'react';
143
143
144
144
function Example() {
145
-
// Declare a new state variable, which we'll call "count"
145
+
// Declarar uma nova variável de state, na qual chamaremos de "count"
146
146
const [count, setCount] = useState(0);
147
147
```
148
148
149
-
We declare a state variable called `count`, and set it to `0`. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current `count`, we can call`setCount`.
149
+
Nós declaramos uma variável state chamada `count`, e definimos ela para 0. React vai lembrar o valor atual entre cada re-renderização, e fornecer o valor mais recente para nossa função. Se quisermos atualizar o `count` atual, podemos chamar`setCount`.
150
150
151
-
>Note
151
+
>Nota
152
152
>
153
-
>You might be wondering: why is `useState`not named `createState` instead?
153
+
>Você pode estar se perguntando: Por que é chamado `useState`ao invés de `createState`?
154
154
>
155
-
>"Create" wouldn't be quite accurate because the state is only created the first time our component renders. During the next renders, `useState`gives us the current state. Otherwise it wouldn't be "state" at all! There's also a reason why Hook names *always* start with `use`. We'll learn why later in the [Rules of Hooks](/docs/hooks-rules.html).
155
+
>"Create" não seria muito preciso porque o state é criado apenas na primeira vez que nosso componente renderiza. Durante as próximas renderizações, `useState`nos da o state atual. Caso contrário, não seria "state" de qualquer maneira! Também tem outro motivo pelo qual nomes de Hook sempre começam com `use`. Vmoas aprender porque depois nas [Regras dos Hooks](/docs/hooks-rules.html).
156
156
157
-
## Reading State {#reading-state}
157
+
## Lendo o State {#reading-state}
158
158
159
-
When we want to display the current count in a class, we read`this.state.count`:
159
+
Quando queremos mostrar o count atual em classe, lemos`this.state.count`:
160
160
161
161
```js
162
162
<p>You clicked {this.state.count} times</p>
163
163
```
164
164
165
-
In a function, we can use `count` directly:
166
-
165
+
Em uma função, podemos usar `count` diretamente:
167
166
168
167
```js
169
168
<p>You clicked {count} times</p>
170
169
```
171
170
172
-
## Updating State {#updating-state}
171
+
## Atualizando o State {#updating-state}
173
172
174
-
In a class, we need to call `this.setState()`to update the `count` state:
173
+
Em uma classe, podemos chamar `this.setState()`para atualizar o state `count`:
In a function, we already have `setCount`and`count`as variables so we don't need`this`:
181
+
Na função, já temos `setCount`e`count`como variáveis então não precisamos do`this`:
183
182
184
183
```js{1}
185
184
<button onClick={() => setCount(count + 1)}>
186
185
Click me
187
186
</button>
188
187
```
189
188
190
-
## Recap {#recap}
189
+
## Recapitulação {#recap}
191
190
192
-
Let's now **recap what we learned line by line**and check our understanding.
191
+
Vamos **recapitular o que aprendemos linha por linha**e checar nosso entendimento.
193
192
194
193
<!--
195
194
I'm not proud of this line markup. Please somebody fix this.
@@ -212,62 +211,62 @@ Let's now **recap what we learned line by line** and check our understanding.
212
211
14: }
213
212
```
214
213
215
-
***Line 1:**We import the`useState`Hook from React. It lets us keep local state in a function component.
216
-
***Line 4:**Inside the `Example` component, we declare a new state variable by calling the `useState` Hook. It returns a pair of values, to which we give names. We're calling our variable`count`because it holds the number of button clicks. We initialize it to zero by passing `0` as the only `useState` argument. The second returned item is itself a function. It lets us update the`count`so we'll name it`setCount`.
217
-
***Line 9:**When the user clicks, we call `setCount`with a new value. React will then re-render the `Example` component, passing the new `count`value to it.
214
+
***Linha 1:**Importamos o Hook`useState`do React. Ele nos permite manter o state local em um componente de função.
215
+
***Linha 4:**Dentro do componente `Example`, declaramos uma nova variável de state chamando o Hook `useState`. Ele retorna um par de valores, no qual damos nomes. Estamos chamando nossa variável`count`porque ela mantém o número de cliques no botão. Inicializamos como zero passando 0 como o único argumento do `useState`. O segundo item retornado é a própria função. Ela nos permite atualizar o`count`então nomeamos para`setCount`.
216
+
***Linha 9:**Quando o usuário clica, chamamos `setCount`com um novo valor. O React então vai re-renderizar o componente `Example`, passando o novo valor de `count`para ele.
218
217
219
-
This might seem like a lot to take in at first. Don't rush it! If you're lost in the explanation, look at the code above again and try to read it from top to bottom. We promise that once you try to "forget" how state works in classes, and look at this code with fresh eyes, it will make sense.
218
+
À primeira vista pode parecer muita coisa. Não se apresse! Se você está perdido na explicação, olhe o código acima novamente e tente lê-lo de uma ponta a outra. Prometemos que a partir do momento que você "esquecer" como state funciona em classes, e olhar este código com novos olhos, irá fazer sentido.
220
219
221
-
### Tip: What Do Square Brackets Mean? {#tip-what-do-square-brackets-mean}
220
+
### Dica: O que os colchetes significam? {#tip-what-do-square-brackets-mean}
222
221
223
-
You might have noticed the square brackets when we declare a state variable:
222
+
Você pode ter percebido os colchetes quando declaramos a variável state:
224
223
225
224
```js
226
225
const [count, setCount] =useState(0);
227
226
```
228
227
229
-
The names on the left aren't a part of the React API. You can name your own state variables:
228
+
Os nomes na esquerda não são parte da API do React. Você pode nomear suas prórias variáveis `state`:
230
229
231
230
```js
232
231
const [fruit, setFruit] =useState('banana');
233
232
```
234
233
235
-
This JavaScript syntax is called["array destructuring"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring). It means that we're making two new variables `fruit`and`setFruit`, where`fruit`is set to the first value returned by`useState`, and`setFruit`is the second. It is equivalent to this code:
234
+
Esta sintaxe do JavaScript é chamada de["atribuição via desestruturação"](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Atribuicao_via_desestruturacao). Significa que estamos fazendo duas novas variáveis `fruit`e`setFruit`, onde`fruit`é definido para o primeiro valor retornado por`useState`, e`setFruit`é o segundo. É equivalente a este código:
236
235
237
236
```js
238
-
var fruitStateVariable =useState('banana'); //Returns a pair
239
-
var fruit = fruitStateVariable[0]; //First item in a pair
240
-
var setFruit = fruitStateVariable[1]; //Second item in a pair
237
+
var fruitStateVariable =useState('banana'); //Retorna um par
238
+
var fruit = fruitStateVariable[0]; //Primeiro item no par
239
+
var setFruit = fruitStateVariable[1]; //Segundo item no par
241
240
```
242
241
243
-
When we declare a state variable with `useState`, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using`[0]`and`[1]`to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.
242
+
Quando declaramos uma variável com `useState`, ela retorna um par - um array com dois itens. O primeiro item é o valor atual e o segundo é uma função que nos permite atualizá-la. Usar`[0]`e`[1]`para acessá-las é um pouco confuso porque elas tem um significado específico. É por isto que utilizamos atribuição via desestruturação no lugar.
244
243
245
-
>Note
244
+
>Nota
246
245
>
247
-
>You might be curious how React knows which component `useState`corresponds to since we're not passing anything like `this`back to React. We'll answer [this question](/docs/hooks-faq.html#how-does-react-associate-hook-calls-with-components)and many others in the FAQ section.
246
+
>Você pode estar curioso como o React sabe qual componente o `useState`corresponde já que não passamos nada como `this`para o React. Vamos responder [esta pergunta](/docs/hooks-faq.html#how-does-react-associate-hook-calls-with-components)e muitas outras na seção FAQ.
248
247
249
-
### Tip: Using Multiple State Variables {#tip-using-multiple-state-variables}
248
+
### Dica: Usando múltiplas variáveis State {#tip-using-multiple-state-variables}
250
249
251
-
Declaring state variables as a pair of`[something, setSomething]`is also handy because it lets us give *different* names to different state variables if we want to use more than one:
250
+
Declarar variáveis de state como par de`[something, setSomething]`também é útil porque nos permite dar *diferentes* nomes para diferentes váriaveis de state se quiséssemos usar mais de uma:
In the above component, we have `age`, `fruit`, and`todos`as local variables, and we can update them individually:
260
+
No componente acima, temos `age`, `fruit` e`todos`como variáveis locais e podemos atualizá-las individualmente:
262
261
263
262
```js
264
263
functionhandleOrangeClick() {
265
-
// Similar to this.setState({ fruit: 'orange' })
264
+
// Similar ao this.setState({ fruit: 'orange' })
266
265
setFruit('orange');
267
266
}
268
267
```
269
268
270
-
You **don't have to** use many state variables. State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike `this.setState`in a class, updating a state variable always *replaces* it instead of merging it.
269
+
Você **não tem que** usar muitas variáveis de state. Elas podem conter objetos e arrays muito bem, portanto você ainda pode juntar dados relacionados. De qualquer maneira, diferente de `this.setState`em classe, atualizar uma variável de state sempre é *substituida* ao invés de incorpora-la
271
270
272
271
We provide more recommendations on splitting independent state variables [in the FAQ](/docs/hooks-faq.html#should-i-use-one-or-many-state-variables).
0 commit comments