Skip to content

Commit 09378f8

Browse files
committed
Translation of Scaling up with reducer and context
1 parent e8bdd9e commit 09378f8

File tree

1 file changed

+55
-54
lines changed

1 file changed

+55
-54
lines changed

beta/src/content/learn/scaling-up-with-reducer-and-context.md

Lines changed: 55 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
---
2-
title: Scaling Up with Reducer and Context
2+
title: Escalando con Reducer y Context
33
---
44

55
<Intro>
66

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.
88

99
</Intro>
1010

1111
<YouWillLearn>
1212

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
1616

1717
</YouWillLearn>
1818

19-
## Combining a reducer with context {/*combining-a-reducer-with-context*/}
19+
## Combininandi un reducer con un context {/*combining-a-reducer-with-context*/}
2020

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:
2222

2323
<Sandpack>
2424

@@ -207,9 +207,9 @@ ul, li { margin: 0; padding: 0; }
207207

208208
</Sandpack>
209209

210-
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.
211211

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`:
213213

214214
```js
215215
<TaskList
@@ -229,30 +229,30 @@ And `TaskList` passes the event handlers to `Task`:
229229
/>
230230
```
231231

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!
233233

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"**.
235235

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:
237237

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.
241241

242-
### Step 1: Create the context {/*step-1-create-the-context*/}
242+
### Paso 1: Creaar el context {/*step-1-create-the-context*/}
243243

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:
245245

246246
```js
247247
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
248248
```
249249

250-
To pass them down the tree, you will [create](/learn/passing-data-deeply-with-context#step-2-use-the-context) two separate contexts:
250+
Para pasarlos por el árbol, tienes [create](/learn/passing-data-deeply-with-context#step-2-use-the-context) dos context distintos:
251251

252-
- `TasksContext` provides the current list of tasks.
253-
- `TasksDispatchContext` provides the function that lets components dispatch actions.
252+
- El `TasksContext` proporciona la lista actual de tareas.
253+
- `TasksDispatchContext` proporciona la función que permite a los componentes enviar acciones.
254254

255-
Export them from a separate file so that you can later import them from other files:
255+
Expórtalos desde un archivo separado para poder importarlos posteriormente desde otros archivos:
256256

257257
<Sandpack>
258258

@@ -448,11 +448,11 @@ ul, li { margin: 0; padding: 0; }
448448

449449
</Sandpack>
450450

451-
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`.
452452

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*/}
454454

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::
456456

457457
```js {4,7-8}
458458
import { TasksContext, TasksDispatchContext } from './TasksContext.js';
@@ -470,7 +470,7 @@ export default function TaskApp() {
470470
}
471471
```
472472

473-
For now, you pass the information both via props and in context:
473+
Por ahora, se pasa la información tanto vía props como en context:
474474

475475
<Sandpack>
476476

@@ -669,11 +669,11 @@ ul, li { margin: 0; padding: 0; }
669669

670670
</Sandpack>
671671

672-
In the next step, you will remove prop passing.
672+
En el siguiente paso, se eliminará el paso del prop.
673673

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*/}
675675

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:
677677

678678
```js {4-5}
679679
<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
685685
</TasksContext.Provider>
686686
```
687687

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`:
689689

690690
```js {2}
691691
export default function TaskList() {
692692
const tasks = useContext(TasksContext);
693693
// ...
694694
```
695695
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:
697697
698698
```js {3,9-13}
699699
export default function AddTask() {
@@ -713,7 +713,7 @@ export default function AddTask() {
713713
// ...
714714
```
715715
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:
717717
718718
<Sandpack>
719719
@@ -897,11 +897,11 @@ ul, li { margin: 0; padding: 0; }
897897
898898
</Sandpack>
899899
900-
**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.
901901
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*/}
903903
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:
905905
906906
```js
907907
import { createContext } from 'react';
@@ -910,11 +910,12 @@ export const TasksContext = createContext(null);
910910
export const TasksDispatchContext = createContext(null);
911911
```
912912
913-
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:
914914
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.
918919
919920
```js
920921
export function TasksProvider({ children }) {
@@ -930,7 +931,7 @@ export function TasksProvider({ children }) {
930931
}
931932
```
932933
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`:**
934935
935936
<Sandpack>
936937
@@ -1121,7 +1122,7 @@ ul, li { margin: 0; padding: 0; }
11211122
11221123
</Sandpack>
11231124
1124-
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`:
11251126
11261127
```js
11271128
export function useTasks() {
@@ -1133,14 +1134,14 @@ export function useTasksDispatch() {
11331134
}
11341135
```
11351136
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:
11371138
11381139
```js
11391140
const tasks = useTasks();
11401141
const dispatch = useTasksDispatch();
11411142
```
11421143
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:**
11441145
11451146
<Sandpack>
11461147
@@ -1340,23 +1341,23 @@ ul, li { margin: 0; padding: 0; }
13401341
13411342
</Sandpack>
13421343
1343-
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.
13441345
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.
13461347
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.
13481349
13491350
<Recap>
13501351
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.
13601361
13611362
</Recap>
13621363

0 commit comments

Comments
 (0)