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: beta/src/content/learn/scaling-up-with-reducer-and-context.md
+55-54Lines changed: 55 additions & 54 deletions
Original file line number
Diff line number
Diff line change
@@ -1,24 +1,24 @@
1
1
---
2
-
title: Scaling Up with Reducer and Context
2
+
title: Escalando con Reducer y Context
3
3
---
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
+
Los Reducers permiten consolidar la lógica de actualización del estado de un componente. El context te permite pasar información en profundidad a otros componentes. Puedes combinar los reducers y el context para gestionar el estado de una pantalla compleja.
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
+
*Cómo combinar un reducer con el context
14
+
*Cómo evitar pasar el state y el dispatch a través de props
15
+
*Cómo mantener la lógica del context y del estado en un archivo separado
16
16
17
17
</YouWillLearn>
18
18
19
-
## Combining a reducer with context {/*combining-a-reducer-with-context*/}
19
+
## Combininandi un reducer con un context {/*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
+
En este ejemplo de [Introducción a reducers](/learn/extracting-state-logic-into-a-reducer), el estado es gestionado por un reducer. La función reducer contiene toda la lógica de actualización del estado y se declara al final de este archivo:
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
+
Un reducer ayuda a mantener los handlers de eventos cortos y concisos. Sin embargo, a medida que tu aplicación crece, puedes encontrarte con otra dificultad. **Actualmente, el estado de las `tareas` y la función`dispatch`sólo están disponibles en el componente de nivel superior `TaskApp`.**Para permitir que otros componentes lean la lista de tareas o la modifiquen, tiene que explicitar [pass down](/learn/passing-props-to-a-component)el estado actual y los handlers de eventos que lo cambian como props.
211
211
212
-
For example, `TaskApp`passes a list of tasks and the event handlers to`TaskList`:
212
+
Por ejemplo, `TaskApp`pasa una lista de tareas y los handlers de eventos a`TaskList`:
213
213
214
214
```js
215
215
<TaskList
@@ -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
+
En un ejemplo pequeño como éste, esto funciona bien, pero si tienes decenas o cientos de componentes en el medio, ¡pasar todo el estado y las funciones puede ser bastante frustrante!
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
+
Por eso, como alternativa a pasarlas por props, podrías poner tanto el estado `tasks`como la función`dispatch`[en context.](/learn/passing-data-deeply-with-context)**De esta manera, cualquier componente por debajo de `TaskApp`en el árbol puede leer las tareas y enviar acciones sin la repetitiva "prop drilling"**.
235
235
236
-
Here is how you can combine a reducer with context:
236
+
A continuación se explica cómo se puede combinar un reducer con el contexto:
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.**Crear**el context.
239
+
2.**Poner**el estado y el envío en el context.
240
+
3.**Utilizar**el context en cualquier parte del árbol.
241
241
242
-
### Step 1: Create the context {/*step-1-create-the-context*/}
242
+
### Paso 1: Creaar el context {/*step-1-create-the-context*/}
243
243
244
-
The `useReducer`Hook returns the current `tasks` and the`dispatch`function that lets you update them:
244
+
El hook `useReducer`devuelve las tareas actuales y la función`dispatch`que permite actualizarlas:
Here, you're passing`null`as the default value to both contexts. The actual values will be provided by the`TaskApp` component.
451
+
Aquí, estás pasando`null`como valor por defecto a ambos context. Los valores reales serán proporcionados por el componente`TaskApp`.
452
452
453
-
### Step 2: Put state and dispatch into context {/*step-2-put-state-and-dispatch-into-context*/}
453
+
### Paso 2: Poner en contexto el state y el 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
+
Ahora puedes importar ambos context en tu componente`TaskApp`. Toma las `tareas` y`dispatch`devueltas por`useReducer()`y [proporciónalas](/learn/passing-data-deeply-with-context#step-3-provide-the-context)a todo el árbol de abajo::
En el siguiente paso, se eliminará el paso del prop.
673
673
674
-
### Step 3: Use context anywhere in the tree {/*step-3-use-context-anywhere-in-the-tree*/}
674
+
### Paso 3: Utilizar el context en cualquier parte del árbol {/*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
+
Ahora no es necesario pasar la lista de tareas o los handlers de eventos por el árbol:
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
+
En cambio, cualquier componente que necesite la lista de tareas puede leerla del`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
+
Para actualizar la lista de tareas, cualquier componente puede leer la función `dispatch`del context y llamarla:
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
+
**El componente `TaskApp`no pasa ningún handler de eventos hacia abajo, y el`TaskList`tampoco pasa ningún handler de eventos al componente`Task`.** Cada componente lee el context que necesita:
**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
+
**El estado todavía "vive" en el componente de nivel superior `TaskApp`, gestionado con`useReducer`.** Pero sus `tareas` y`dispatch`están ahora disponibles para todos los componentes por debajo en el árbol mediante la importación y el uso de estos context.
901
901
902
-
## Moving all wiring into a single file {/*moving-all-wiring-into-a-single-file*/}
902
+
## Trasladar todo la lógica a un único archivo {/*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
+
No es necesario que lo hagas, pero podrías simplificar aún más los componentes moviendo tanto el reducer como el context a un solo archivo. Actualmente, `TasksContext.js`contiene sólo dos declaraciones de contexto:
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
+
¡Este archivo está a punto de complicarse! Moverás el reducer a ese mismo archivo. A continuación, declararás un nuevo componente `TasksProvider`en el mismo archivo. Este componente unirá todas las piezas:
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. Gestionará el estado con un reducer.
916
+
2. Proporcionará ambos context a los componentes de abajo.
917
+
3. Tomará como prop a los `hijos`.
918
+
3. [Tomará como prop a los `hijos`](/learn/passing-props-to-a-component#passing-jsx-as-children) para que puedas pasarlo a JSX.
918
919
919
920
```js
920
921
exportfunctionTasksProvider({ children }) {
@@ -930,7 +931,7 @@ export function TasksProvider({ children }) {
930
931
}
931
932
```
932
933
933
-
**This removes all the complexity and wiring from your `TaskApp` component:**
934
+
**Esto elimina toda la complejidad y la lógica del componente `TaskApp`:**
You can also export functions that _use_ the context from`TasksContext.js`:
1125
+
También puedes exportar funciones que _utilicen_ el context desde`TasksContext.js`:
1125
1126
1126
1127
```js
1127
1128
exportfunctionuseTasks() {
@@ -1133,14 +1134,14 @@ export function useTasksDispatch() {
1133
1134
}
1134
1135
```
1135
1136
1136
-
When a component needs to read context, it can do it through these functions:
1137
+
Cuando un componente necesita leer el context, puede hacerlo a través de estas funciones:
1137
1138
1138
1139
```js
1139
1140
consttasks=useTasks();
1140
1141
constdispatch=useTasksDispatch();
1141
1142
```
1142
1143
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:**
1144
+
Esto no cambia el comportamiento de ninguna manera, pero te permite dividir más tarde estos context o añadir algo de lógica a estas funciones. **Ahora todo la lógica del contexto y del reducer está en `TasksContext.js`. Esto mantiene los componentes limpios y despejados, centrados en lo que muestran en lugar de donde obtienen los datos:**
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.
1344
+
Puedes pensar en `TasksProvider`como una parte de la pantalla que sabe cómo tratar con las tareas, `useTasks`como una forma de leerlas, y`useTasksDispatch`como una forma de actualizarlas desde cualquier componente de abajo en el árbol.
1344
1345
1345
-
> 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.
1346
+
> Funciones como`useTasks`y`useTasksDispatch`se llaman **[Hooks personalizados (Custom Hooks).](/learn/reusing-logic-with-custom-hooks)** Tu función se considera un Hook personalizado si su nombre empieza por `use`. Esto te permite usar otros Hooks, como`useContext`, dentro de ella.
1346
1347
1347
-
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.
1348
+
A medida que tu aplicación crece, puedes tener muchos pares context-reducer como este. Esta es una poderosa forma de escalar tu aplicación y [manejar el estado](/learn/sharing-state-between-components) sin demasiado trabajo cada vez que se quiera acceder a los datos en la profundidad del árbol.
1348
1349
1349
1350
<Recap>
1350
1351
1351
-
- You can combine reducer with context to let any component read and update state above it.
1352
-
- To provide state and the dispatch function to components below:
1353
-
1. Create two contexts (for state and for dispatch functions).
1354
-
2. Provide both contexts from the component that uses the reducer.
1355
-
3. Use either context from components that need to read them.
1356
-
- You can further declutter the components by moving all wiring into one file.
1357
-
- You can export a component like `TasksProvider`that provides context.
1358
-
- You can also export custom Hooks like `useTasks`and`useTasksDispatch`to read it.
1359
-
- You can have many context-reducer pairs like this in your app.
1352
+
- Puedes combinar el reducer con el context para permitir que cualquier componente lea y actualice el estado por encima de él.
1353
+
- Para proporcionar el estado y la función de envío a los componentes de abajo:
1354
+
1. Cree dos context (para el state y para las funciones de dispatch).
1355
+
2. Proporcione ambos context desde el componente que utiliza el reducer.
1356
+
3. Utiliza cualquiera de los dos context desde los componentes que necesiten leerlos.
1357
+
- Puedes refactorizar aún más los componentes moviendo todo la lógica a un solo archivo.
1358
+
- Puedes exportar un componente como `TasksProvider`que proporciona el context.
1359
+
- También puedes exportar hooks personalizados como `useTasks`y`useTasksDispatch`para leerlo.
1360
+
- Puedes tener muchos pares context-reducer como este en tu aplicación.
0 commit comments