From eb8deb321bf2813ededb5b89ad552dcf1fb9d38a Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Wed, 4 Feb 2026 15:05:03 +0000 Subject: [PATCH 1/3] =?UTF-8?q?docs:=20translate=20`extracting-state-logic?= =?UTF-8?q?-into-a-reducer.md`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../extracting-state-logic-into-a-reducer.md | 962 ++---------------- 1 file changed, 84 insertions(+), 878 deletions(-) diff --git a/src/content/learn/extracting-state-logic-into-a-reducer.md b/src/content/learn/extracting-state-logic-into-a-reducer.md index 5c08c01239..65e6ad4b05 100644 --- a/src/content/learn/extracting-state-logic-into-a-reducer.md +++ b/src/content/learn/extracting-state-logic-into-a-reducer.md @@ -1,25 +1,25 @@ --- -title: Extracting State Logic into a Reducer +title: Вынесение логики состояния в редьюсер --- -Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a _reducer._ +Компоненты с большим количеством обновлений состояния, распределённых по множеству обработчиков событий, могут стать неуправляемыми. В таких случаях всю логику обновления состояния можно вынести за пределы компонента в одну функцию, называемую _редьюсером._ -- What a reducer function is -- How to refactor `useState` to `useReducer` -- When to use a reducer -- How to write one well +- Что такое функция-редьюсер +- Как перейти от `useState` к `useReducer` +- Когда следует использовать редьюсер +- Как правильно его написать -## Consolidate state logic with a reducer {/*consolidate-state-logic-with-a-reducer*/} +## Объедините логику состояния с помощью редьюсера {/*consolidate-state-logic-with-a-reducer*/} -As your components grow in complexity, it can get harder to see at a glance all the different ways in which a component's state gets updated. For example, the `TaskApp` component below holds an array of `tasks` in state and uses three different event handlers to add, remove, and edit tasks: +По мере усложнения ваших компонентов становится труднее с первого взгляда увидеть все способы обновления состояния компонента. Например, компонент `TaskApp` ниже содержит массив `tasks` в состоянии и использует три разных обработчика событий для добавления, удаления и редактирования задач: @@ -106,390 +106,41 @@ export default function AddTask({onAddTask}) { ```js src/TaskList.js hidden import { useState } from 'react'; -export default function TaskList({tasks, onChangeTask, onDeleteTask}) { - return ( - - ); -} - -function Task({task, onChange, onDelete}) { - const [isEditing, setIsEditing] = useState(false); - let taskContent; - if (isEditing) { - taskContent = ( - <> - { - onChange({ - ...task, - text: e.target.value, - }); - }} - /> - - - ); - } else { - taskContent = ( - <> - {task.text} - - - ); - } - return ( - - ); -} -``` - -```css -button { - margin: 5px; -} -li { - list-style-type: none; -} -ul, -li { - margin: 0; - padding: 0; -} -``` - - - -Each of its event handlers calls `setTasks` in order to update the state. As this component grows, so does the amount of state logic sprinkled throughout it. To reduce this complexity and keep all your logic in one easy-to-access place, you can move that state logic into a single function outside your component, **called a "reducer".** - -Reducers are a different way to handle state. You can migrate from `useState` to `useReducer` in three steps: - -1. **Move** from setting state to dispatching actions. -2. **Write** a reducer function. -3. **Use** the reducer from your component. - -### Step 1: Move from setting state to dispatching actions {/*step-1-move-from-setting-state-to-dispatching-actions*/} - -Your event handlers currently specify _what to do_ by setting state: - -```js -function handleAddTask(text) { - setTasks([ - ...tasks, - { - id: nextId++, - text: text, - done: false, - }, - ]); -} - -function handleChangeTask(task) { - setTasks( - tasks.map((t) => { - if (t.id === task.id) { - return task; - } else { - return t; - } - }) - ); -} - -function handleDeleteTask(taskId) { - setTasks(tasks.filter((t) => t.id !== taskId)); -} -``` - -Remove all the state setting logic. What you are left with are three event handlers: - -- `handleAddTask(text)` is called when the user presses "Add". -- `handleChangeTask(task)` is called when the user toggles a task or presses "Save". -- `handleDeleteTask(taskId)` is called when the user presses "Delete". - -Managing state with reducers is slightly different from directly setting state. Instead of telling React "what to do" by setting state, you specify "what the user just did" by dispatching "actions" from your event handlers. (The state update logic will live elsewhere!) So instead of "setting `tasks`" via an event handler, you're dispatching an "added/changed/deleted a task" action. This is more descriptive of the user's intent. - -```js -function handleAddTask(text) { - dispatch({ - type: 'added', - id: nextId++, - text: text, - }); -} - -function handleChangeTask(task) { - dispatch({ - type: 'changed', - task: task, - }); -} - -function handleDeleteTask(taskId) { - dispatch({ - type: 'deleted', - id: taskId, - }); -} -``` - -The object you pass to `dispatch` is called an "action": - -```js {3-7} -function handleDeleteTask(taskId) { - dispatch( - // "action" object: - { - type: 'deleted', - id: taskId, - } - ); -} -``` - -It is a regular JavaScript object. You decide what to put in it, but generally it should contain the minimal information about _what happened_. (You will add the `dispatch` function itself in a later step.) - - - -An action object can have any shape. - -By convention, it is common to give it a string `type` that describes what happened, and pass any additional information in other fields. The `type` is specific to a component, so in this example either `'added'` or `'added_task'` would be fine. Choose a name that says what happened! - -```js -dispatch({ - // specific to component - type: 'what_happened', - // other fields go here -}); -``` - - - -### Step 2: Write a reducer function {/*step-2-write-a-reducer-function*/} - -A reducer function is where you will put your state logic. It takes two arguments, the current state and the action object, and it returns the next state: - -```js -function yourReducer(state, action) { - // return next state for React to set -} -``` - -React will set the state to what you return from the reducer. - -To move your state setting logic from your event handlers to a reducer function in this example, you will: - -1. Declare the current state (`tasks`) as the first argument. -2. Declare the `action` object as the second argument. -3. Return the _next_ state from the reducer (which React will set the state to). - -Here is all the state setting logic migrated to a reducer function: - -```js -function tasksReducer(tasks, action) { - if (action.type === 'added') { - return [ - ...tasks, - { - id: action.id, - text: action.text, - done: false, - }, - ]; - } else if (action.type === 'changed') { - return tasks.map((t) => { - if (t.id === action.task.id) { - return action.task; - } else { - return t; - } - }); - } else if (action.type === 'deleted') { - return tasks.filter((t) => t.id !== action.id); - } else { - throw Error('Unknown action: ' + action.type); - } -} -``` - -Because the reducer function takes state (`tasks`) as an argument, you can **declare it outside of your component.** This decreases the indentation level and can make your code easier to read. - - - -The code above uses if/else statements, but it's a convention to use [switch statements](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/switch) inside reducers. The result is the same, but it can be easier to read switch statements at a glance. - -We'll be using them throughout the rest of this documentation like so: - -```js -function tasksReducer(tasks, action) { - switch (action.type) { - case 'added': { - return [ - ...tasks, - { - id: action.id, - text: action.text, - done: false, - }, - ]; - } - case 'changed': { - return tasks.map((t) => { - if (t.id === action.task.id) { - return action.task; - } else { - return t; - } - }); - } - case 'deleted': { - return tasks.filter((t) => t.id !== action.id); - } - default: { - throw Error('Unknown action: ' + action.type); - } - } -} -``` - -We recommend wrapping each `case` block into the `{` and `}` curly braces so that variables declared inside of different `case`s don't clash with each other. Also, a `case` should usually end with a `return`. If you forget to `return`, the code will "fall through" to the next `case`, which can lead to mistakes! - -If you're not yet comfortable with switch statements, using if/else is completely fine. - - - - - -#### Why are reducers called this way? {/*why-are-reducers-called-this-way*/} - -Although reducers can "reduce" the amount of code inside your component, they are actually named after the [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) operation that you can perform on arrays. - -The `reduce()` operation lets you take an array and "accumulate" a single value out of many: - -``` -const arr = [1, 2, 3, 4, 5]; -const sum = arr.reduce( - (result, number) => result + number -); // 1 + 2 + 3 + 4 + 5 -``` - -The function you pass to `reduce` is known as a "reducer". It takes the _result so far_ and the _current item,_ then it returns the _next result._ React reducers are an example of the same idea: they take the _state so far_ and the _action_, and return the _next state._ In this way, they accumulate actions over time into state. - -You could even use the `reduce()` method with an `initialState` and an array of `actions` to calculate the final state by passing your reducer function to it: - - - -```js src/index.js active -import tasksReducer from './tasksReducer.js'; - -let initialState = []; -let actions = [ - {type: 'added', id: 1, text: 'Visit Kafka Museum'}, - {type: 'added', id: 2, text: 'Watch a puppet show'}, - {type: 'deleted', id: 1}, - {type: 'added', id: 3, text: 'Lennon Wall pic'}, -]; - -let finalState = actions.reduce(tasksReducer, initialState); - -const output = document.getElementById('output'); -output.textContent = JSON.stringify(finalState, null, 2); -``` - -```js src/tasksReducer.js -export default function tasksReducer(tasks, action) { - switch (action.type) { - case 'added': { - return [ - ...tasks, - { - id: action.id, - text: action.text, - done: false, - }, - ]; - } - case 'changed': { - return tasks.map((t) => { - if (t.id === action.task.id) { - return action.task; - } else { - return t; - } - }); - } - case 'deleted': { - return tasks.filter((t) => t.id !== action.id); - } - default: { - throw Error('Unknown action: ' + action.type); - } - } -} -``` - -```html public/index.html -

-```
-
-
+export default function TaskList({tasks, onChangeTask, -You probably won't need to do this yourself, but this is similar to what React does! +### Шаг 3: Используйте reducer в вашем компоненте {/*step-3-use-the-reducer-from-your-component*/} -
- -### Step 3: Use the reducer from your component {/*step-3-use-the-reducer-from-your-component*/} - -Finally, you need to hook up the `tasksReducer` to your component. Import the `useReducer` Hook from React: +Наконец, вам нужно подключить `tasksReducer` к вашему компоненту. Импортируйте хук `useReducer` из React: ```js import { useReducer } from 'react'; ``` -Then you can replace `useState`: +Затем вы можете заменить `useState`: ```js const [tasks, setTasks] = useState(initialTasks); ``` -with `useReducer` like so: +на `useReducer` следующим образом: ```js const [tasks, dispatch] = useReducer(tasksReducer, initialTasks); ``` -The `useReducer` Hook is similar to `useState`—you must pass it an initial state and it returns a stateful value and a way to set state (in this case, the dispatch function). But it's a little different. +Хук `useReducer` похож на `useState` — вы должны передать ему начальное состояние, и он возвращает значение состояния и способ его установки (в данном случае, функцию `dispatch`). Но есть небольшое отличие. -The `useReducer` Hook takes two arguments: +Хук `useReducer` принимает два аргумента: -1. A reducer function -2. An initial state +1. Функция-reducer +2. Начальное состояние -And it returns: +И возвращает: -1. A stateful value -2. A dispatch function (to "dispatch" user actions to the reducer) +1. Значение состояния +2. Функция `dispatch` (для "отправки" действий пользователя в reducer) -Now it's fully wired up! Here, the reducer is declared at the bottom of the component file: +Теперь всё подключено! Здесь reducer объявлен внизу файла компонента: @@ -674,7 +325,7 @@ li { -If you want, you can even move the reducer to a different file: +При желании вы можете вынести reducer в отдельный файл: @@ -862,30 +513,30 @@ li { -Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify _what happened_ by dispatching actions, and the reducer function determines _how the state updates_ in response to them. +Логику компонента легче читать, когда вы разделяете обязанности. Теперь обработчики событий только указывают, _что произошло_, отправляя действия, а функция reducer определяет, _как состояние обновляется_ в ответ на них. -## Comparing `useState` and `useReducer` {/*comparing-usestate-and-usereducer*/} +## Сравнение `useState` и `useReducer` {/*comparing-usestate-and-usereducer*/} -Reducers are not without downsides! Here's a few ways you can compare them: +Редьюсеры не лишены недостатков! Вот несколько способов их сравнить: -- **Code size:** Generally, with `useState` you have to write less code upfront. With `useReducer`, you have to write both a reducer function _and_ dispatch actions. However, `useReducer` can help cut down on the code if many event handlers modify state in a similar way. -- **Readability:** `useState` is very easy to read when the state updates are simple. When they get more complex, they can bloat your component's code and make it difficult to scan. In this case, `useReducer` lets you cleanly separate the _how_ of update logic from the _what happened_ of event handlers. -- **Debugging:** When you have a bug with `useState`, it can be difficult to tell _where_ the state was set incorrectly, and _why_. With `useReducer`, you can add a console log into your reducer to see every state update, and _why_ it happened (due to which `action`). If each `action` is correct, you'll know that the mistake is in the reducer logic itself. However, you have to step through more code than with `useState`. -- **Testing:** A reducer is a pure function that doesn't depend on your component. This means that you can export and test it separately in isolation. While generally it's best to test components in a more realistic environment, for complex state update logic it can be useful to assert that your reducer returns a particular state for a particular initial state and action. -- **Personal preference:** Some people like reducers, others don't. That's okay. It's a matter of preference. You can always convert between `useState` and `useReducer` back and forth: they are equivalent! +- **Размер кода:** Как правило, с `useState` вы пишете меньше кода изначально. С `useReducer` вам нужно написать как функцию-редьюсер, _так и_ отправлять действия (actions). Однако `useReducer` может помочь сократить код, если многие обработчики событий изменяют состояние схожим образом. +- **Читаемость:** `useState` очень легко читать, когда обновления состояния просты. Когда они становятся сложнее, они могут раздувать код вашего компонента и затруднять его сканирование. В этом случае `useReducer` позволяет чисто разделить _как_ логика обновления происходит от _что произошло_ в обработчиках событий. +- **Отладка:** Когда у вас возникает ошибка с `useState`, бывает трудно понять, _где_ состояние было установлено неправильно и _почему_. С `useReducer` вы можете добавить `console.log` в ваш редьюсер, чтобы увидеть каждое обновление состояния и _почему_ оно произошло (из-за какого `action`). Если каждое `action` корректно, вы будете знать, что ошибка заключается в самой логике редьюсера. Однако вам придется проходить через больше кода, чем с `useState`. +- **Тестирование:** Редьюсер — это чистая функция, которая не зависит от вашего компонента. Это означает, что вы можете экспортировать и тестировать ее отдельно, в изоляции. Хотя в целом лучше тестировать компоненты в более реалистичной среде, для сложной логики обновления состояния может быть полезно убедиться, что ваш редьюсер возвращает определенное состояние для определенного начального состояния и действия. +- **Личные предпочтения:** Некоторым нравятся редьюсеры, другим — нет. Это нормально. Это вопрос предпочтений. Вы всегда можете конвертировать `useState` в `useReducer` и обратно: они эквивалентны! -We recommend using a reducer if you often encounter bugs due to incorrect state updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even `useState` and `useReducer` in the same component. +Мы рекомендуем использовать редьюсер, если вы часто сталкиваетесь с ошибками из-за неправильных обновлений состояния в каком-либо компоненте и хотите привнести больше структуры в его код. Вам не обязательно использовать редьюсеры для всего: смешивайте и сочетайте по своему усмотрению! Вы можете даже использовать `useState` и `useReducer` в одном компоненте. -## Writing reducers well {/*writing-reducers-well*/} +## Правильное написание редьюсеров {/*writing-reducers-well*/} -Keep these two tips in mind when writing reducers: +При написании редьюсеров помните эти два совета: -- **Reducers must be pure.** Similar to [state updater functions](/learn/queueing-a-series-of-state-updates), reducers run during rendering! (Actions are queued until the next render.) This means that reducers [must be pure](/learn/keeping-components-pure)—same inputs always result in the same output. They should not send requests, schedule timeouts, or perform any side effects (operations that impact things outside the component). They should update [objects](/learn/updating-objects-in-state) and [arrays](/learn/updating-arrays-in-state) without mutations. -- **Each action describes a single user interaction, even if that leads to multiple changes in the data.** For example, if a user presses "Reset" on a form with five fields managed by a reducer, it makes more sense to dispatch one `reset_form` action rather than five separate `set_field` actions. If you log every action in a reducer, that log should be clear enough for you to reconstruct what interactions or responses happened in what order. This helps with debugging! +- **Редьюсеры должны быть чистыми.** Подобно [функциям обновления состояния](/learn/queueing-a-series-of-state-updates), редьюсеры выполняются во время рендеринга! (Действия ставятся в очередь до следующего рендеринга.) Это означает, что редьюсеры [должны быть чистыми](/learn/keeping-components-pure)—одинаковые входные данные всегда должны приводить к одинаковому результату. Они не должны отправлять запросы, планировать тайм-ауты или выполнять какие-либо побочные эффекты (операции, влияющие на что-то вне компонента). Они должны обновлять [объекты](/learn/updating-objects-in-state) и [массивы](/learn/updating-arrays-in-state) без мутаций. +- **Каждое действие описывает одно взаимодействие пользователя, даже если это приводит к нескольким изменениям в данных.** Например, если пользователь нажимает «Сбросить» в форме с пятью полями, управляемыми редьюсером, имеет больше смысла отправить одно действие `reset_form`, а не пять отдельных действий `set_field`. Если вы регистрируете каждое действие в редьюсере, этот лог должен быть достаточно ясным, чтобы вы могли восстановить, какие взаимодействия или ответы произошли и в каком порядке. Это помогает при отладке! -## Writing concise reducers with Immer {/*writing-concise-reducers-with-immer*/} +## Написание лаконичных редюсеров с Immer {/*writing-concise-reducers-with-immer*/} -Just like with [updating objects](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) and [arrays](/learn/updating-arrays-in-state#write-concise-update-logic-with-immer) in regular state, you can use the Immer library to make reducers more concise. Here, [`useImmerReducer`](https://github.com/immerjs/use-immer#useimmerreducer) lets you mutate the state with `push` or `arr[i] =` assignment: +Как и при [обновлении объектов](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) и [массивов](/learn/updating-arrays-in-state#write-concise-update-logic-with-immer) в обычном состоянии, вы можете использовать библиотеку Immer, чтобы сделать редюсеры более лаконичными. Здесь [`useImmerReducer`](https://github.com/immerjs/use-immer#useimmerreducer) позволяет изменять состояние с помощью `push` или присваивания `arr[i] =`: @@ -1082,34 +733,34 @@ li { -Reducers must be pure, so they shouldn't mutate state. But Immer provides you with a special `draft` object which is safe to mutate. Under the hood, Immer will create a copy of your state with the changes you made to the `draft`. This is why reducers managed by `useImmerReducer` can mutate their first argument and don't need to return state. +Редюсеры должны быть чистыми, поэтому они не должны изменять состояние. Но Immer предоставляет специальный объект `draft`, который безопасно изменять. Под капотом Immer создаст копию вашего состояния с изменениями, которые вы внесли в `draft`. Именно поэтому редюсеры, управляемые `useImmerReducer`, могут изменять свой первый аргумент и им не нужно возвращать состояние. -- To convert from `useState` to `useReducer`: - 1. Dispatch actions from event handlers. - 2. Write a reducer function that returns the next state for a given state and action. - 3. Replace `useState` with `useReducer`. -- Reducers require you to write a bit more code, but they help with debugging and testing. -- Reducers must be pure. -- Each action describes a single user interaction. -- Use Immer if you want to write reducers in a mutating style. +- Чтобы перейти от `useState` к `useReducer`: + 1. Отправляйте действия из обработчиков событий. + 2. Напишите функцию-редюсер, которая возвращает следующее состояние для данного состояния и действия. + 3. Замените `useState` на `useReducer`. +- Редюсеры требуют написания немного большего кода, но они помогают при отладке и тестировании. +- Редюсеры должны быть чистыми. +- Каждое действие описывает одно взаимодействие пользователя. +- Используйте Immer, если хотите писать редюсеры в изменяемом стиле. -#### Dispatch actions from event handlers {/*dispatch-actions-from-event-handlers*/} +#### Отправка действий из обработчиков событий {/*dispatch-actions-from-event-handlers*/} -Currently, the event handlers in `ContactList.js` and `Chat.js` have `// TODO` comments. This is why typing into the input doesn't work, and clicking on the buttons doesn't change the selected recipient. +В настоящее время обработчики событий в `ContactList.js` и `Chat.js` содержат комментарии `// TODO`. Именно поэтому ввод текста в поле не работает, а нажатие на кнопки не меняет выбранного получателя. -Replace these two `// TODO`s with the code to `dispatch` the corresponding actions. To see the expected shape and the type of the actions, check the reducer in `messengerReducer.js`. The reducer is already written so you won't need to change it. You only need to dispatch the actions in `ContactList.js` and `Chat.js`. +Замените эти два `// TODO` кодом для отправки соответствующих действий. Чтобы увидеть ожидаемую структуру и тип действий, проверьте редюсер в `messengerReducer.js`. Редюсер уже написан, поэтому вам не нужно его менять. Вам нужно только отправить действия в `ContactList.js` и `Chat.js`. -The `dispatch` function is already available in both of these components because it was passed as a prop. So you need to call `dispatch` with the corresponding action object. +Функция `dispatch` уже доступна в обоих этих компонентах, так как она была передана как проп. Поэтому вам нужно вызвать `dispatch` с соответствующим объектом действия. -To check the action object shape, you can look at the reducer and see which `action` fields it expects to see. For example, the `changed_selection` case in the reducer looks like this: +Чтобы проверить структуру объекта действия, вы можете посмотреть на редюсер и увидеть, какие поля `action` он ожидает увидеть. Например, случай `changed_selection` в редюсере выглядит так: ```js case 'changed_selection': { @@ -1120,7 +771,7 @@ case 'changed_selection': { } ``` -This means that your action object should have a `type: 'changed_selection'`. You also see the `action.contactId` being used, so you need to include a `contactId` property into your action. +Это означает, что ваш объект действия должен иметь `type: 'changed_selection'`. Вы также видите использование `action.contactId`, поэтому вам нужно включить свойство `contactId` в ваше действие. @@ -1256,23 +907,23 @@ textarea { -From the reducer code, you can infer that actions need to look like this: +Из кода редюсера вы можете сделать вывод, что действия должны выглядеть так: ```js -// When the user presses "Alice" +// Когда пользователь нажимает "Alice" dispatch({ type: 'changed_selection', contactId: 1, }); -// When user types "Hello!" +// Когда пользователь вводит "Hello!" dispatch({ type: 'edited_message', message: 'Hello!', }); ``` -Here is the example updated to dispatch the corresponding messages: +Вот пример, обновленный для отправки соответствующих сообщений: @@ -1411,487 +1062,42 @@ textarea { -#### Clear the input on sending a message {/*clear-the-input-on-sending-a-message*/} - -Currently, pressing "Send" doesn't do anything. Add an event handler to the "Send" button that will: - -1. Show an `alert` with the recipient's email and the message. -2. Clear the message input. - - - -```js src/App.js -import { useReducer } from 'react'; -import Chat from './Chat.js'; -import ContactList from './ContactList.js'; -import { initialState, messengerReducer } from './messengerReducer'; +#### Очистка поля ввода при отправке сообщения {/*clear-the-input-on-sending-a-message*/} -export default function Messenger() { - const [state, dispatch] = useReducer(messengerReducer, initialState); - const message = state.message; - const contact = contacts.find((c) => c.id === state.selectedId); - return ( -
- - -
- ); -} - -const contacts = [ - {id: 0, name: 'Taylor', email: 'taylor@mail.com'}, - {id: 1, name: 'Alice', email: 'alice@mail.com'}, - {id: 2, name: 'Bob', email: 'bob@mail.com'}, -]; -``` - -```js src/messengerReducer.js -export const initialState = { - selectedId: 0, - message: 'Hello', -}; - -export function messengerReducer(state, action) { - switch (action.type) { - case 'changed_selection': { - return { - ...state, - selectedId: action.contactId, - message: '', - }; - } - case 'edited_message': { - return { - ...state, - message: action.message, - }; - } - default: { - throw Error('Unknown action: ' + action.type); - } - } -} -``` - -```js src/ContactList.js -export default function ContactList({contacts, selectedId, dispatch}) { - return ( -
-
    - {contacts.map((contact) => ( -
  • - -
  • - ))} -
-
- ); -} -``` - -```js src/Chat.js active -import { useState } from 'react'; - -export default function Chat({contact, message, dispatch}) { - return ( -
-