```js src/App.js
-import { useReducer } from 'react';
+import { useReducer } from './MyReact.js';
import Chat from './Chat.js';
import ContactList from './ContactList.js';
import { initialState, messengerReducer } from './messengerReducer';
export default function Messenger() {
const [state, dispatch] = useReducer(messengerReducer, initialState);
- const message = state.message;
+ const message = state.messages[state.selectedId];
const contact = contacts.find((c) => c.id === state.selectedId);
return (
@@ -1411,12 +1413,12 @@ textarea {
-#### Clear the input on sending a message {/*clear-the-input-on-sending-a-message*/}
+#### Limpar o campo ao enviar uma mensagem {/*clear-the-input-on-sending-a-message*/}
-Currently, pressing "Send" doesn't do anything. Add an event handler to the "Send" button that will:
+Atualmente, pressionar "Enviar" não faz nada. Adicione um manipulador de eventos ao botão "Enviar" que irá:
-1. Show an `alert` with the recipient's email and the message.
-2. Clear the message input.
+1. Mostrar um `alert` com o email do destinatário e a mensagem.
+2. Limpar o campo de mensagem.
@@ -1555,7 +1557,7 @@ textarea {
-There are a couple of ways you could do it in the "Send" button event handler. One approach is to show an alert and then dispatch an `edited_message` action with an empty `message`:
+Existem algumas maneiras de fazer isso no manipulador de eventos do botão "Enviar". Uma abordagem é mostrar um alerta e então despachar uma ação `edited_message` com uma `message` vazia:
@@ -1701,9 +1703,9 @@ textarea {
-This works and clears the input when you hit "Send".
+Isso funciona e limpa o campo quando você clica em "Send".
-However, _from the user's perspective_, sending a message is a different action than editing the field. To reflect that, you could instead create a _new_ action called `sent_message`, and handle it separately in the reducer:
+No entanto, _da perspectiva do usuário_, enviar uma mensagem é uma ação diferente de editar o campo. Para refletir isso, você poderia criar uma _nova_ ação chamada `sent_message` e tratá-la separadamente no reducer:
@@ -1854,28 +1856,28 @@ textarea {
-The resulting behavior is the same. But keep in mind that action types should ideally describe "what the user did" rather than "how you want the state to change". This makes it easier to later add more features.
+O comportamento resultante é o mesmo. Mas tenha em mente que os tipos de ação devem idealmente descrever "o que o usuário fez" em vez de "como você quer que o estado mude". Isso torna mais fácil adicionar mais recursos posteriormente.
-With either solution, it's important that you **don't** place the `alert` inside a reducer. The reducer should be a pure function--it should only calculate the next state. It should not "do" anything, including displaying messages to the user. That should happen in the event handler. (To help catch mistakes like this, React will call your reducers multiple times in Strict Mode. This is why, if you put an alert in a reducer, it fires twice.)
+Com qualquer uma das soluções, é importante que você **não** coloque o `alert` dentro de um reducer. O reducer deve ser uma função pura--ele deve apenas calcular o próximo estado. Ele não deve "fazer" nada, incluindo exibir mensagens para o usuário. Isso deve acontecer no manipulador de eventos. (Para ajudar a detectar erros como este, o React chamará seus reducers várias vezes no Modo Estrito. É por isso que, se você colocar um alert em um reducer, ele dispara duas vezes.)
-#### Restore input values when switching between tabs {/*restore-input-values-when-switching-between-tabs*/}
+#### Restaurar valores de entrada ao alternar entre abas {/*restore-input-values-when-switching-between-tabs*/}
-In this example, switching between different recipients always clears the text input:
+Neste exemplo, alternar entre diferentes destinatários sempre limpa a entrada de texto:
```js
case 'changed_selection': {
return {
...state,
selectedId: action.contactId,
- message: '' // Clears the input
+ message: '' // Limpa a entrada
};
```
-This is because you don't want to share a single message draft between several recipients. But it would be better if your app "remembered" a draft for each contact separately, restoring them when you switch contacts.
+Isso ocorre porque você não quer compartilhar um único rascunho de mensagem entre vários destinatários. Mas seria melhor se seu aplicativo "lembrasse" um rascunho para cada contato separadamente, restaurando-os quando você alterna entre contatos.
-Your task is to change the way the state is structured so that you remember a separate message draft _per contact_. You would need to make a few changes to the reducer, the initial state, and the components.
+Sua tarefa é alterar a forma como o estado está estruturado para que você lembre um rascunho de mensagem separado _por contato_. Você precisará fazer algumas alterações no reducer, no estado inicial e nos componentes.
@@ -1885,13 +1887,13 @@ You can structure your state like this:
export const initialState = {
selectedId: 0,
messages: {
- 0: 'Hello, Taylor', // Draft for contactId = 0
- 1: 'Hello, Alice', // Draft for contactId = 1
+ 0: 'Hello, Taylor', // Rascunho para contactId = 0
+ 1: 'Hello, Alice', // Rascunho para contactId = 1
},
};
```
-The `[key]: value` [computed property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) syntax can help you update the `messages` object:
+A sintaxe de [propriedade computada](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) `[chave]: valor` pode ajudar você a atualizar o objeto `messages`:
```js
{
@@ -1972,7 +1974,7 @@ export function messengerReducer(state, action) {
}
```
-```js src/ContactList.js
+```js src/ContactList.js hidden
export default function ContactList({contacts, selectedId, dispatch}) {
return (
@@ -1996,7 +1998,7 @@ export default function ContactList({contacts, selectedId, dispatch}) {
}
```
-```js src/Chat.js
+```js src/Chat.js hidden
import { useState } from 'react';
export default function Chat({contact, message, dispatch}) {
@@ -2053,31 +2055,31 @@ textarea {
-You'll need to update the reducer to store and update a separate message draft per contact:
+Você precisará atualizar o reducer para armazenar e atualizar um rascunho de mensagem separado para cada destinatário:
```js
-// When the input is edited
+// Quando a entrada é editada
case 'edited_message': {
return {
- // Keep other state like selection
+ // Mantém outros estados como seleção
...state,
messages: {
- // Keep messages for other contacts
+ // Mantém mensagens para outros contatos
...state.messages,
- // But change the selected contact's message
+ // Mas altera a mensagem do contato selecionado
[state.selectedId]: action.message
}
};
}
```
-You would also update the `Messenger` component to read the message for the currently selected contact:
+Você também precisará atualizar o componente `Messenger` para ler a mensagem para o destinatário selecionado:
```js
const message = state.messages[state.selectedId];
```
-Here is the complete solution:
+Aqui está a solução completa:
@@ -2237,19 +2239,19 @@ textarea {
-Notably, you didn't need to change any of the event handlers to implement this different behavior. Without a reducer, you would have to change every event handler that updates the state.
+Notavelmente, você não precisou alterar nenhum dos manipuladores de eventos para implementar esse comportamento diferente. Sem um reducer, você teria que alterar cada manipulador de evento que atualiza o estado.
-#### Implement `useReducer` from scratch {/*implement-usereducer-from-scratch*/}
+#### Implemente `useReducer` do zero {/*implement-usereducer-from-scratch*/}
-In the earlier examples, you imported the `useReducer` Hook from React. This time, you will implement _the `useReducer` Hook itself!_ Here is a stub to get you started. It shouldn't take more than 10 lines of code.
+Nos exemplos anteriores, você importou o Hook `useReducer` do React. Desta vez, você irá implementar _o próprio Hook `useReducer`!_ Aqui está um esboço para você começar. Não deve levar mais de 10 linhas de código.
-To test your changes, try typing into the input or select a contact.
+Para testar suas alterações, tente digitar na entrada ou selecionar um contato.
-Here is a more detailed sketch of the implementation:
+Aqui está um esboço mais detalhado da implementação:
```js
export function useReducer(reducer, initialState) {
@@ -2263,7 +2265,7 @@ export function useReducer(reducer, initialState) {
}
```
-Recall that a reducer function takes two arguments--the current state and the action object--and it returns the next state. What should your `dispatch` implementation do with it?
+Lembre-se que uma função reducer recebe dois argumentos--o estado atual e o objeto de ação--e retorna o próximo estado. O que sua implementação de `dispatch` deve fazer com isso?
@@ -2614,7 +2616,7 @@ textarea {
-Though it doesn't matter in most cases, a slightly more accurate implementation looks like this:
+Embora não faça diferença na maioria dos casos, uma implementação um pouco mais precisa se parece com isso:
```js
function dispatch(action) {
@@ -2622,7 +2624,7 @@ function dispatch(action) {
}
```
-This is because the dispatched actions are queued until the next render, [similar to the updater functions.](/learn/queueing-a-series-of-state-updates)
+Isso ocorre porque as ações despachadas são enfileiradas até a próxima renderização, [semelhante às funções de atualização.](/learn/queueing-a-series-of-state-updates)