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
{/* TODO T164397693: link to actions documentation once it exists */}
31
30
32
-
Call`useActionState`at the top level of your component to create component state that is updated [when a form action is invoked](/reference/react-dom/components/form). You pass `useActionState`an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state and whether the Action is still pending. The latest form state is also passed to the function that you provided.
31
+
Chame`useActionState`no nível superior do seu componente para criar um estado do componente que é atualizado [quando uma ação de formulário é invocada](/reference/react-dom/components/form). Você passa para o `useActionState`uma função de ação de formulário existente, bem como um estado inicial, e ele retorna uma nova ação que você usa no seu formulário, juntamente com o estado atual do formulário e se a ação ainda está pendente. O estado atual do formulário também é passado para a função que você forneceu.
33
32
34
33
```js
35
34
import { useActionState } from"react";
@@ -49,40 +48,40 @@ function StatefulForm({}) {
49
48
}
50
49
```
51
50
52
-
The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.
51
+
O estado do formulário é o valor retornado pela ação quando o formulário foi enviado pela última vez. Se o formulário ainda não foi enviado, é o estado inicial que você passa.
53
52
54
-
If used with a Server Function, `useActionState`allows the server's response from submitting the form to be shown even before hydration has completed.
53
+
Quando usado com uma Função de Servidor, `useActionState`permite que a resposta do servidor ao enviar o formulário seja exibida mesmo antes da hidratação ser concluída.
55
54
56
-
[See more examples below.](#usage)
55
+
[Veja mais exemplos abaixo.](#usage)
57
56
58
-
#### Parameters {/*parameters*/}
57
+
#### Parâmetros {/*parameters*/}
59
58
60
-
* `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the`initialState`that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
61
-
* `initialState`: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
62
-
* **optional** `permalink`: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if`fn`is a [server function](/reference/rsc/server-functions) and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page's URL. Ensure that the same form component is rendered on the destination page (including the same action `fn`and `permalink`) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.
59
+
* `fn`: A função a ser chamada quando o formulário é enviado ou o botão pressionado. Quando a função é chamada, ela receberá o estado anterior do formulário (inicialmente o`initialState`que você passa, subsequentemente seu valor de retorno anterior) como seu primeiro argumento, seguido pelos argumentos que uma ação de formulário normalmente recebe.
60
+
* `initialState`: O valor que você deseja que o estado seja inicialmente. Pode ser qualquer valor serializável. Este argumento é ignorado depois que a ação é invocada pela primeira vez.
61
+
* **opcional** `permalink`: Uma string contendo a URL exclusiva da página que este formulário modifica. Para uso em páginas com conteúdo dinâmico (por exemplo: feeds) em conjunto com aprimoramento progressivo: se`fn`é uma [função de servidor](/reference/rsc/server-functions) e o formulário é enviado antes do carregamento do bundle JavaScript, o navegador navegará para a URL de permalink especificada, em vez da URL da página atual. Garanta que o mesmo componente de formulário seja renderizado na página de destino (incluindo a mesma `fn`de ação e `permalink`) para que o React saiba como passar o estado. Uma vez que o formulário tenha sido hidratado, este parâmetro não tem efeito.
63
62
64
63
{/* TODO T164397693: link to serializable values docs once it exists */}
65
64
66
-
#### Returns {/*returns*/}
65
+
#### Retornos {/*returns*/}
67
66
68
-
`useActionState`returns an array with the following values:
67
+
`useActionState`retorna um array com os seguintes valores:
69
68
70
-
1. The current state. During the first render, it will match the `initialState`you have passed. After the action is invoked, it will match the value returned by the action.
71
-
2. A new action that you can pass as the `action`prop to your`form`component or `formAction`prop to any`button`component within the form. The action can also be called manually within [`startTransition`](/reference/react/startTransition).
72
-
3. The `isPending`flag that tells you whether there is a pending Transition.
69
+
1. O estado atual. Durante a primeira renderização, ele corresponderá ao `initialState`que você passou. Depois que a ação for invocada, ele corresponderá ao valor retornado pela action.
70
+
2. Uma nova ação que você pode passar como a prop `action`para seu componente`form`ou a prop `formAction`para qualquer componente`button`dentro do formulário. A ação também pode ser chamada manualmente dentro de [`startTransition`](/reference/react/startTransition).
71
+
3. A flag `isPending`que informa se existe uma Transition pendente.
73
72
74
-
#### Caveats {/*caveats*/}
73
+
#### Ressalvas {/*caveats*/}
75
74
76
-
* When used with a framework that supports React Server Components, `useActionState`lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state.
77
-
* The function passed to`useActionState`receives an extra argument, the previous or initial state, as its first argument. This makes its signature different than if it were used directly as a form action without using`useActionState`.
75
+
* Quando usado com um framework que oferece suporte a React Server Components, `useActionState`permite que você torne os formulários interativos antes que o JavaScript tenha sido executado no cliente. Quando usado sem Server Components, é equivalente ao estado local do componente.
76
+
* A função passada para`useActionState`recebe um argumento extra, o estado anterior ou inicial, como seu primeiro argumento. Isso torna sua assinatura diferente do que se fosse usado diretamente como uma ação de formulário sem usar`useActionState`.
78
77
79
78
---
80
79
81
-
## Usage {/*usage*/}
80
+
## Uso {/*usage*/}
82
81
83
-
### Using information returned by a form action {/*using-information-returned-by-a-form-action*/}
82
+
### Usando informações retornadas por uma ação de formulário {/*using-information-returned-by-a-form-action*/}
84
83
85
-
Call`useActionState`at the top level of your component to access the return value of an action from the last time a form was submitted.
84
+
Chame`useActionState`no nível superior do seu componente para acessar o valor de retorno de uma action da última vez que um formulário foi enviado.
`useActionState`returns an array with the following items:
101
+
`useActionState`retorna um array com os seguintes itens:
103
102
104
-
1. The <CodeStep step={1}>current state</CodeStep> of the form, which is initially set to the <CodeStep step={4}>initial state</CodeStep> you provided, and after the form is submitted is set to the return value of the <CodeStep step={3}>action</CodeStep> you provided.
105
-
2. A <CodeStep step={2}>new action</CodeStep> that you pass to `<form>`as its `action`prop or call manually within`startTransition`.
106
-
3. A <CodeStep step={1}>pending state</CodeStep> that you can utilise while your action is processing.
103
+
1. O <CodeStep step={1}>estado atual</CodeStep> do formulário, que é inicialmente definido como o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu e, após o formulário ser enviado, é definido como o valor de retorno da <CodeStep step={3}>ação</CodeStep> que você forneceu.
104
+
2. Uma <CodeStep step={2}>nova ação</CodeStep> que você passa para o `<form>`como sua prop `action`ou chama manualmente dentro de`startTransition`.
105
+
3. Um <CodeStep step={1}>estado pendente</CodeStep> que você pode utilizar enquanto sua ação está processando.
107
106
108
-
When the form is submitted, the <CodeStep step={3}>action</CodeStep> function that you provided will be called. Its return value will become the new <CodeStep step={1}>current state</CodeStep> of the form.
107
+
Quando o formulário é enviado, a função <CodeStep step={3}>ação</CodeStep> que você forneceu será chamada. Seu valor de retorno se tornará o novo <CodeStep step={1}>estado atual</CodeStep> do formulário.
109
108
110
-
The <CodeStep step={3}>action</CodeStep> that you provide will also receive a new first argument, namely the <CodeStep step={1}>current state</CodeStep> of the form. The first time the form is submitted, this will be the <CodeStep step={4}>initial state</CodeStep> you provided, while with subsequent submissions, it will be the return value from the last time the action was called. The rest of the arguments are the same as if `useActionState`had not been used.
109
+
A <CodeStep step={3}>ação</CodeStep> que você fornece também receberá um novo primeiro argumento, ou seja, o <CodeStep step={1}>estado atual</CodeStep> do formulário. Na primeira vez que o formulário for enviado, este será o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu, enquanto com envios subsequentes, será o valor de retorno da última vez que a action foi chamada. O restante dos argumentos são os mesmos de se `useActionState`não tivesse sido usado.
111
110
112
111
```js [[3, 1, "action"], [1, 1, "currentState"]]
113
112
functionaction(currentState, formData) {
@@ -116,11 +115,11 @@ function action(currentState, formData) {
116
115
}
117
116
```
118
117
119
-
<Recipes titleText="Display information after submitting a form" titleId="display-information-after-submitting-a-form">
118
+
<Recipes titleText="Exibir informações após o envio de um formulário" titleId="display-information-after-submitting-a-form">
120
119
121
-
#### Display form errors {/*display-form-errors*/}
120
+
#### Exibir erros de formulário {/*display-form-errors*/}
122
121
123
-
To display messages such as an error message or toast that's returned by a Server Function, wrap the action in a call to`useActionState`.
122
+
Para exibir mensagens como uma mensagem de erro ou toast que é retornado por uma Server Function, envolva a ação em uma chamada para`useActionState`.
124
123
125
124
<Sandpack>
126
125
@@ -182,9 +181,9 @@ form button {
182
181
183
182
<Solution />
184
183
185
-
#### Display structured information after submitting a form {/*display-structured-information-after-submitting-a-form*/}
184
+
#### Exibir informações estruturadas após o envio de um formulário {/*display-structured-information-after-submitting-a-form*/}
186
185
187
-
The return value from a Server Function can be any serializable value. For example, it could be an object that includes a boolean indicating whether the action was successful, an error message, or updated information.
186
+
O valor de retorno de uma Server Function pode ser qualquer valor serializável. Por exemplo, pode ser um objeto que inclui um booleano indicando se a ação foi bem-sucedida, uma mensagem de erro ou informações atualizadas.
188
187
189
188
<Sandpack>
190
189
@@ -259,14 +258,14 @@ form button {
259
258
260
259
</Recipes>
261
260
262
-
## Troubleshooting {/*troubleshooting*/}
261
+
## Solução de problemas {/*troubleshooting*/}
263
262
264
-
### My action can no longer read the submitted form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}
263
+
### Minha action não consegue mais ler os dados do formulário enviado {/*my-action-can-no-longer-read-the-submitted-form-data*/}
265
264
266
-
When you wrap an action with`useActionState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current state of the form.
265
+
Quando você envolve uma action com`useActionState`, ela recebe um argumento extra *como seu primeiro argumento*. Os dados do formulário enviado são, portanto, seu *segundo* argumento em vez de seu primeiro, como seria normalmente. O novo primeiro argumento que é adicionado é o estado atual do formulário.
0 commit comments