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: src/content/learn/scaling-up-with-reducer-and-context.md
+56-57Lines changed: 56 additions & 57 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,21 +4,21 @@ title: Scaling Up with Reducer and Context
4
4
5
5
<Intro>
6
6
7
-
Reducers let you consolidate a component's state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen.
7
+
Редьюсеры позволяют вам объединить логику обновления состояния компонента. Контекст позволяет передавать информацию глубоко другим компонентам. Вы можете объединить редьюсеры и контекст вместе для управления состоянием сложного экрана.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearn>
12
12
13
-
*How to combine a reducer with context
14
-
*How to avoid passing state and dispatch through props
15
-
*How to keep context and state logic in a separate file
13
+
*Как объединить редьюсер с контекстом
14
+
*Как избежать передачи состояния и `dispatch` через пропсы
15
+
*Как вынести логику контекста и состояния в отдельный файл
16
16
17
17
</YouWillLearn>
18
18
19
-
## Combining a reducer with context {/*combining-a-reducer-with-context*/}
19
+
## Объединение редьюсера с контекстом {/*combining-a-reducer-with-context*/}
20
20
21
-
In this example from [the introduction to reducers](/learn/extracting-state-logic-into-a-reducer), the state is managed by a reducer. The reducer function contains all of the state update logic and is declared at the bottom of this file:
21
+
В этом примере из [введения в редьюсеры](/learn/extracting-state-logic-into-a-reducer) состояние управляется редьюсером. Функция редьюсера содержит всю логику обновления состояния и объявлена внизу этого файла:
A reducer helps keep the event handlers short and concise. However, as your app grows, you might run into another difficulty. **Currently, the `tasks`state and the `dispatch`function are only available in the top-level `TaskApp` component.**To let other components read the list of tasks or change it, you have to explicitly [pass down](/learn/passing-props-to-a-component)the current state and the event handlers that change it as props.
210
+
Редьюсер помогает сделать обработчики событий короткими и лаконичными. Однако, по мере роста вашего приложения, вы можете столкнуться с другой трудностью. **В настоящее время состояние `tasks`и функция `dispatch`доступны только в компоненте верхнего уровня `TaskApp`.**Чтобы позволить другим компонентам читать список задач или изменять его, вам придется явно [передавать вниз](/learn/passing-props-to-a-component)текущее состояние и обработчики событий, которые его изменяют, в виде пропсов.
211
211
212
-
For example, `TaskApp`passes a list of tasks and the event handlers to`TaskList`:
212
+
Например, `TaskApp`передает список задач и обработчики событий в`TaskList`:
213
213
214
214
```js
215
215
<TaskList
@@ -219,7 +219,7 @@ For example, `TaskApp` passes a list of tasks and the event handlers to `TaskLis
219
219
/>
220
220
```
221
221
222
-
And`TaskList`passes the event handlers to`Task`:
222
+
А`TaskList`передает обработчики событий в`Task`:
223
223
224
224
```js
225
225
<Task
@@ -229,30 +229,30 @@ And `TaskList` passes the event handlers to `Task`:
229
229
/>
230
230
```
231
231
232
-
In a small example like this, this works well, but if you have tens or hundreds of components in the middle, passing down all state and functions can be quite frustrating!
232
+
В таком небольшом примере это работает хорошо, но если у вас есть десятки или сотни компонентов посередине, передача всех состояний и функций может быть довольно утомительной!
233
233
234
-
This is why, as an alternative to passing them through props, you might want to put both the `tasks` state and the`dispatch`function [into context.](/learn/passing-data-deeply-with-context)**This way, any component below`TaskApp`in the tree can read the tasks and dispatch actions without the repetitive "prop drilling".**
234
+
Вот почему, в качестве альтернативы передаче через пропсы, вы можете поместить как состояние `tasks`, так и функцию`dispatch`[в контекст.](/learn/passing-data-deeply-with-context)**Таким образом, любой компонент ниже`TaskApp`в дереве сможет читать задачи и отправлять действия без повторяющейся "проп-дрелинг".**
235
235
236
-
Here is how you can combine a reducer with context:
236
+
Вот как вы можете объединить редьюсер с контекстом:
237
237
238
-
1.**Create**the context.
239
-
2.**Put**state and dispatch into context.
240
-
3.**Use**context anywhere in the tree.
238
+
1.**Создайте**контекст.
239
+
2.**Поместите**состояние и `dispatch` в контекст.
240
+
3.**Используйте**контекст в любом месте дерева.
241
241
242
-
### Step 1: Create the context {/*step-1-create-the-context*/}
Here, you're passing`null`as the default value to both contexts. The actual values will be provided by the `TaskApp` component.
451
+
Здесь вы передаете`null`в качестве значения по умолчанию для обоих контекстов. Фактические значения будут предоставлены компонентом `TaskApp`.
452
452
453
-
### Step 2: Put state and dispatch into context {/*step-2-put-state-and-dispatch-into-context*/}
453
+
### Шаг 2: Поместите состояние и `dispatch` в контекст {/*step-2-put-state-and-dispatch-into-context*/}
454
454
455
-
Now you can import both contexts in your `TaskApp` component. Take the `tasks`and`dispatch` returned by `useReducer()` and [provide them](/learn/passing-data-deeply-with-context#step-3-provide-the-context)to the entire tree below:
455
+
Теперь вы можете импортировать оба контекста в вашем компоненте `TaskApp`. Возьмите `tasks`и`dispatch`, возвращаемые `useReducer()`, и [предоставьте их](/learn/passing-data-deeply-with-context#step-3-provide-the-context)всему дереву ниже:
### Step 3: Use context anywhere in the tree {/*step-3-use-context-anywhere-in-the-tree*/}
674
+
### Шаг 3: Используйте контекст в любом месте дерева {/*step-3-use-context-anywhere-in-the-tree*/}
675
675
676
-
Now you don't need to pass the list of tasks or the event handlers down the tree:
676
+
Теперь вам не нужно передавать список задач или обработчики событий вниз по дереву:
677
677
678
678
```js {4-5}
679
679
<TasksContext.Provider value={tasks}>
@@ -685,15 +685,15 @@ Now you don't need to pass the list of tasks or the event handlers down the tree
685
685
</TasksContext.Provider>
686
686
```
687
687
688
-
Instead, any component that needs the task list can read it from the`TaskContext`:
688
+
Вместо этого любой компонент, которому нужен список задач, может прочитать его из`TaskContext`:
689
689
690
690
```js {2}
691
691
exportdefaultfunctionTaskList() {
692
692
consttasks=useContext(TasksContext);
693
693
// ...
694
694
```
695
695
696
-
To update the task list, any component can read the`dispatch`function from context and call it:
696
+
Чтобы обновить список задач, любой компонент может прочитать функцию`dispatch`из контекста и вызвать ее:
697
697
698
698
```js {3,9-13}
699
699
exportdefaultfunctionAddTask() {
@@ -713,7 +713,7 @@ export default function AddTask() {
713
713
// ...
714
714
```
715
715
716
-
**The`TaskApp`component does not pass any event handlers down, and the `TaskList`does not pass any event handlers to the `Task` component either.** Each component reads the context that it needs:
716
+
**Компонент`TaskApp`не передает никаких обработчиков событий вниз, и `TaskList`также не передает никаких обработчиков событий компоненту `Task`.** Каждый компонент читает нужный ему контекст:
**The state still "lives" in the top-level`TaskApp` component, managed with `useReducer`.** But its`tasks`and`dispatch`are now available to every component below in the tree by importing and using these contexts.
900
+
**Состояние по-прежнему «живет» в компоненте верхнего уровня`TaskApp`, управляемое с помощью `useReducer`.** Но его`tasks`и`dispatch`теперь доступны каждому компоненту ниже в дереве путем импорта и использования этих контекстов.
901
901
902
-
## Moving all wiring into a single file {/*moving-all-wiring-into-a-single-file*/}
902
+
## Перемещение всей логики в один файл {/*moving-all-wiring-into-a-single-file*/}
903
903
904
-
You don't have to do this, but you could further declutter the components by moving both reducer and context into a single file. Currently, `TasksContext.js`contains only two context declarations:
904
+
Вам не обязательно это делать, но вы можете дополнительно упростить компоненты, переместив редьюсер и контекст в один файл. В настоящее время `TasksContext.js`содержит только два объявления контекста:
This file is about to get crowded! You'll move the reducer into that same file. Then you'll declare a new`TasksProvider`component in the same file. This component will tie all the pieces together:
913
+
Этот файл скоро станет перегруженным! Вы переместите редьюсер в тот же файл. Затем вы объявите новый компонент`TasksProvider`в том же файле. Этот компонент объединит все части:
914
914
915
-
1. It will manage the state with a reducer.
916
-
2. It will provide both contexts to components below.
917
-
3. It will [take`children`as a prop](/learn/passing-props-to-a-component#passing-jsx-as-children) so you can pass JSX to it.
915
+
1. Он будет управлять состоянием с помощью редьюсера.
916
+
2. Он предоставит оба контекста компонентам ниже.
917
+
3. Он [примет`children`как проп](/learn/passing-props-to-a-component#passing-jsx-as-children), чтобы вы могли передавать ему JSX.
918
918
919
919
```js
920
920
exportfunctionTasksProvider({ children }) {
@@ -930,7 +930,7 @@ export function TasksProvider({ children }) {
930
930
}
931
931
```
932
932
933
-
**This removes all the complexity and wiring from your`TaskApp` component:**
933
+
**Это убирает всю сложность и логику из вашего компонента`TaskApp`:**
You can also export functions that _use_ the context from`TasksContext.js`:
1124
+
Вы также можете экспортировать функции, которые _используют_ контекст из`TasksContext.js`:
1125
1125
1126
1126
```js
1127
1127
exportfunctionuseTasks() {
@@ -1133,14 +1133,14 @@ export function useTasksDispatch() {
1133
1133
}
1134
1134
```
1135
1135
1136
-
When a component needs to read context, it can do it through these functions:
1136
+
Когда компоненту нужно прочитать контекст, он может сделать это через эти функции:
1137
1137
1138
1138
```js
1139
1139
consttasks=useTasks();
1140
1140
constdispatch=useTasksDispatch();
1141
1141
```
1142
1142
1143
-
This doesn't change the behavior in any way, but it lets you later split these contexts further or add some logic to these functions. **Now all of the context and reducer wiring is in `TasksContext.js`. This keeps the components clean and uncluttered, focused on what they display rather than where they get the data:**
1143
+
Это никак не меняет поведение, но позволяет вам в дальнейшем разделить эти контексты или добавить некоторую логику в эти функции. **Теперь вся логика контекста и редьюсера находится в `TasksContext.js`. Это сохраняет компоненты чистыми и простыми, сосредоточенными на том, что они отображают, а не на том, откуда они получают данные:**
You can think of `TasksProvider`as a part of the screen that knows how to deal with tasks, `useTasks`as a way to read them, and`useTasksDispatch`as a way to update them from any component below in the tree.
1343
+
Вы можете рассматривать `TasksProvider`как часть экрана, которая знает, как работать с задачами, `useTasks`как способ их чтения, а`useTasksDispatch`как способ их обновления из любого компонента ниже в дереве.
1344
1344
1345
1345
<Note>
1346
1346
1347
-
Functions like `useTasks`and`useTasksDispatch` are called *[Custom Hooks.](/learn/reusing-logic-with-custom-hooks)* Your function is considered a custom Hook if its name starts with `use`. This lets you use other Hooks, like `useContext`, inside it.
1347
+
Функции, такие как `useTasks`и`useTasksDispatch`, называются *[Пользовательскими хуками](/learn/reusing-logic-with-custom-hooks)*. Ваша функция считается пользовательским хуком, если её имя начинается с `use`. Это позволяет вам использовать другие хуки, такие как `useContext`, внутри неё.
1348
1348
1349
1349
</Note>
1350
1350
1351
-
As your app grows, you may have many context-reducer pairs like this. This is a powerful way to scale your app and [lift state up](/learn/sharing-state-between-components) without too much work whenever you want to access the data deep in the tree.
1351
+
По мере роста вашего приложения у вас может появиться много пар контекст-редьюсер, подобных этой. Это мощный способ масштабировать ваше приложение и [поднимать состояние вверх](/learn/sharing-state-between-components) без особых усилий, когда бы вы ни захотели получить доступ к данным глубоко в дереве.
1352
1352
1353
1353
<Recap>
1354
1354
1355
-
- You can combine reducer with context to let any component read and update state above it.
1356
-
- To provide state and the dispatch function to components below:
1357
-
1. Create two contexts (for state and for dispatch functions).
1358
-
2. Provide both contexts from the component that uses the reducer.
1359
-
3. Use either context from components that need to read them.
1360
-
- You can further declutter the components by moving all wiring into one file.
1361
-
- You can export a component like `TasksProvider` that provides context.
1362
-
- You can also export custom Hooks like `useTasks` and `useTasksDispatch` to read it.
1363
-
- You can have many context-reducer pairs like this in your app.
1364
-
1365
-
</Recap>
1366
-
1355
+
- Вы можете объединить редьюсер с контекстом, чтобы любой компонент мог читать и обновлять состояние выше него.
1356
+
- Чтобы предоставить состояние и функцию `dispatch` компонентам ниже:
1357
+
1. Создайте два контекста (для состояния и для функций `dispatch`).
1358
+
2. Предоставьте оба контекста из компонента, который использует редьюсер.
1359
+
3. Используйте любой из контекстов в компонентах, которым нужно их читать.
1360
+
- Вы можете дополнительно упростить компоненты, переместив всю логику в один файл.
1361
+
- Вы можете экспортировать компонент, такой как `TasksProvider`, который предоставляет контекст.
1362
+
- Вы также можете экспортировать пользовательские хуки, такие как `useTasks` и `useTasksDispatch`, для его чтения.
1363
+
- В вашем приложении может быть много пар контекст-редьюсер, подобных этой.
0 commit comments