diff --git a/beta/src/content/learn/choosing-the-state-structure.md b/beta/src/content/learn/choosing-the-state-structure.md
index 70969d3fc..de662b50f 100644
--- a/beta/src/content/learn/choosing-the-state-structure.md
+++ b/beta/src/content/learn/choosing-the-state-structure.md
@@ -1,53 +1,53 @@
---
-title: Choosing the State Structure
+title: Elección de la estructura del estado
---
-Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. Here are some tips you should consider when structuring state.
+Estructurar bien el estado puede marcar la diferencia entre un componente que es agradable de modificar y depurar, y uno que es una fuente constante de errores. Estos son algunos consejos que debe tener en cuenta al estructurar el estado.
-* When to use a single vs multiple state variables
-* What to avoid when organizing state
-* How to fix common issues with the state structure
+* Cuando usar una versus múltiples variables de estado.
+* Qué evitar al organizar el estado.
+* Cómo solucionar problemas comunes con la estructura del estado.
-## Principles for structuring state {/*principles-for-structuring-state*/}
+## Principios para la estructuración del estado {/*principles-for-structuring-state*/}
-When you write a component that holds some state, you'll have to make choices about how many state variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal state structure, there are a few principles that can guide you to make better choices:
+Cuando escribes un componente que contiene algún estado, tendrás que tomar decisiones acerca de cuántas variables de estado usar y cuál debería ser la forma de tus datos. Si bien es posible escribir programas correctos incluso con una estructura de estado deficiente, existen algunos principios que pueden guiarte para tomar mejores decisiones:
-1. **Group related state.** If you always update two or more state variables at the same time, consider merging them into a single state variable.
-2. **Avoid contradictions in state.** When the state is structured in a way that several pieces of state may contradict and "disagree" with each other, you leave room for mistakes. Try to avoid this.
-3. **Avoid redundant state.** If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state.
-4. **Avoid duplication in state.** When the same data is duplicated between multiple state variables, or within nested objects, it is difficult to keep them in sync. Reduce duplication when you can.
-5. **Avoid deeply nested state.** Deeply hierarchical state is not very convenient to update. When possible, prefer to structure state in a flat way.
+1. **Estado relacionado con el grupo.** Si siempre actualizas dos o más variables de estado al mismo tiempo, considera fusionarlas en una sola variable de estado.
+2. **Evita las contradicciones en el estado.** Cuando el estado está estructurado de manera que varias partes del estado pueden contradecirse y "estar en desacuerdo" entre sí, deja espacio para errores. Trata de evitar esto.
+3. **Evita el estado redundante.** Si puedes calcular alguna información de las propiedades del componente o sus variables de estado existentes durante el renderizado, no debes poner esa información en el estado de ese componente.
+4. **Evita la duplicación de estado.** Cuando los mismos datos se duplican entre varias variables de estado o dentro de objetos anidados, es difícil mantenerlos sincronizados. Reduce la duplicación cuando puedas.
+5. **Evita el estado profundamente anidado.** El estado profundamente jerárquico no es muy conveniente para actualizar. Cuando sea posible, prefiere estructurar el estado de forma plana.
-The goal behind these principles is to *make state easy to update without introducing mistakes*. Removing redundant and duplicate data from state helps ensure that all its pieces stay in sync. This is similar to how a database engineer might want to ["normalize" the database structure](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) to reduce the chance of bugs. To paraphrase Albert Einstein, **"Make your state as simple as it can be--but no simpler."**
+El objetivo detrás de estos principios es *hacer que el estado sea fácil de actualizar sin introducir errores*. La eliminación de datos redundantes y duplicados del estado ayuda a garantizar que todas sus piezas permanezcan sincronizadas. Esto es similar a cómo un ingeniero de base de datos podría querer ["normalizar" la estructura de la base de datos](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) para reducir la posibilidad de errores. Parafraseando a Albert Einstein, **"Haz que tu estado sea lo más simple posible, pero no más simple".**
-Now let's see how these principles apply in action.
+Ahora veamos cómo se aplican estos principios en acción.
-## Group related state {/*group-related-state*/}
+## Estado relativo al grupo {/*group-related-state*/}
-You might sometimes be unsure between using a single or multiple state variables.
+En ocasiones, es posible que no estés seguro entre usar una o varias variables de estado.
-Should you do this?
+¿Deberías hacer esto?
```js
const [x, setX] = useState(0);
const [y, setY] = useState(0);
```
-Or this?
+¿O esto?
```js
const [position, setPosition] = useState({ x: 0, y: 0 });
```
-Technically, you can use either of these approaches. But **if some two state variables always change together, it might be a good idea to unify them into a single state variable.** Then you won't forget to always keep them in sync, like in this example where moving the cursor updates both coordinates of the red dot:
+Técnicamente, puedes usar cualquiera de estos enfoques. Pero **si algunas de las dos variables de estado siempre cambian juntas, podría ser una buena idea unificarlas en una sola variable de estado.** Entonces no olvidarás mantenerlos siempre sincronizados, como en este ejemplo donde al mover el cursor se actualizan ambas coordenadas del punto rojo:
@@ -93,17 +93,17 @@ body { margin: 0; padding: 0; height: 250px; }
-Another case where you'll group data into an object or an array is when you don't know how many different pieces of state you'll need. For example, it's helpful when you have a form where the user can add custom fields.
+Otro caso en el que agruparás datos en un objeto o una matriz es cuando no sabes cuántas partes diferentes del estado se necesitarán. Por ejemplo, es útil cuando tienes un formulario en el que el usuario puede agregar campos personalizados.
-If your state variable is an object, remember that [you can't update only one field in it](/learn/updating-objects-in-state) without explicitly copying the other fields. For example, you can't do `setPosition({ x: 100 })` in the above example because it would not have the `y` property at all! Instead, if you wanted to set `x` alone, you would either do `setPosition({ ...position, x: 100 })`, or split them into two state variables and do `setX(100)`.
+Si tu variable de estado es un objeto, recuerda que [no se puede actualizar solo un campo en él](/learn/updating-objects-in-state) sin copiar explícitamente los otros campos. Por ejemplo, no puedes hacer `setPosition({ x: 100 })` pues en el ejemplo anterior no tendría la propiedad `y` en ningún lugar. En su lugar, si quisieras establecer solo la propiedad `x`, la definirías así `setPosition({ ...position, x: 100 })`, o las dividirías en dos variables de estado y harías `setX(100)`.
-## Avoid contradictions in state {/*avoid-contradictions-in-state*/}
+## Evitar contradicciones en el estado {/*avoid-contradictions-in-state*/}
-Here is a hotel feedback form with `isSending` and `isSent` state variables:
+Aquí hay un formulario de comentarios de un hotel con variables de estado `isSending` y `isSent`:
@@ -124,12 +124,12 @@ export default function FeedbackForm() {
}
if (isSent) {
- return
Thanks for feedback!
+ return
¡Gracias por tu retroalimentación!
}
return (
);
}
-// Pretend to send a message.
+// Pretender enviar un mensaje.
function sendMessage(text) {
return new Promise(resolve => {
setTimeout(resolve, 2000);
@@ -157,9 +157,9 @@ function sendMessage(text) {
-While this code works, it leaves the door open for "impossible" states. For example, if you forget to call `setIsSent` and `setIsSending` together, you may end up in a situation where both `isSending` and `isSent` are `true` at the same time. The more complex your component is, the harder it will be to understand what happened.
+Si bien este código funciona, deja la puerta abierta para estados "imposibles". Por ejemplo, si olvidas llamar a `setIsSent` y `setIsSending` juntos, puede terminar en una situación en la que tanto `isSending` como `isSent` son `true` al mismo tiempo. Cuanto más complejo sea tu componente, más difícil será entender lo que sucedió.
-**Since `isSending` and `isSent` should never be `true` at the same time, it is better to replace them with one `status` state variable that may take one of *three* valid states:** `'typing'` (initial), `'sending'`, and `'sent'`:
+**Dado que `isSending` y `isSent` nunca deben ser `true` al mismo tiempo, es mejor reemplazarlos con una variable de estado `status` que puede tomar uno de *tres* estados válidos:** `'typing '` (initial), `'sending'` y `'sent'`:
@@ -181,12 +181,12 @@ export default function FeedbackForm() {
const isSent = status === 'sent';
if (isSent) {
- return
Thanks for feedback!
+ return
¡Gracias por tu retroalimentación!
}
return (
);
}
-// Pretend to send a message.
+// Pretender enviar un mensaje.
function sendMessage(text) {
return new Promise(resolve => {
setTimeout(resolve, 2000);
@@ -214,20 +214,20 @@ function sendMessage(text) {
-You can still declare some constants for readability:
+Todavía puedes declarar algunas constantes para mejorar la legibilidad:
```js
const isSending = status === 'sending';
const isSent = status === 'sent';
```
-But they're not state variables, so you don't need to worry about them getting out of sync with each other.
+Pero no son variables de estado, por lo que no debes preocuparte de que no estén sincronizadas entre sí.
-## Avoid redundant state {/*avoid-redundant-state*/}
+## Evitar estado redundante {/*avoid-redundant-state*/}
-If you can calculate some information from the component's props or its existing state variables during rendering, you **should not** put that information into that component's state.
+Si puedes calcular alguna información de las props del componente o sus variables de estado existentes durante el renderizado, **no debes** poner esa información en el estado de ese componente.
-For example, take this form. It works, but can you find any redundant state in it?
+Por ejemplo, toma este formulario. Funciona, pero ¿puedes encontrar algún estado redundante en él?
@@ -251,23 +251,23 @@ export default function Form() {
return (
<>
-
Let’s check you in
+
Vamos a registrarte
- Your ticket will be issued to: {fullName}
+ Su boleto será emitido a:{fullName}
>
);
@@ -280,9 +280,9 @@ label { display: block; margin-bottom: 5px; }
-This form has three state variables: `firstName`, `lastName`, and `fullName`. However, `fullName` is redundant. **You can always calculate `fullName` from `firstName` and `lastName` during render, so remove it from state.**
+Este formulario tiene tres variables de estado: `firstName`, `lastName` y `fullName`. Sin embargo, `fullName` es redundante. **Siempre puedes calcular `fullName` a partir de `firstName` y `lastName` durante el renderizado, así que quítalo del estado.**
-This is how you can do it:
+Así es como puedes hacerlo:
@@ -305,23 +305,23 @@ export default function Form() {
return (
<>
-
Let’s check you in
+
Vamos a registrarte
- Your ticket will be issued to: {fullName}
+ Su boleto será emitido a: {fullName}
>
);
@@ -334,50 +334,50 @@ label { display: block; margin-bottom: 5px; }
-Here, `fullName` is *not* a state variable. Instead, it's calculated during render:
+aquí, `fullName` *no* es una variable de estado. En cambio, se calcula durante el renderizado:
```js
const fullName = firstName + ' ' + lastName;
```
-As a result, the change handlers don't need to do anything special to update it. When you call `setFirstName` or `setLastName`, you trigger a re-render, and then the next `fullName` will be calculated from the fresh data.
+Como resultado, los controladores de cambios no necesitan hacer nada especial para actualizarlo. Cuando llamas a `setFirstName` o `setLastName`, activas una nueva representación y luego el siguiente `fullName` se calculará a partir de los nuevos datos.
-#### Don't mirror props in state {/*don-t-mirror-props-in-state*/}
+#### No reflejar props en el estado {/*don-t-mirror-props-in-state*/}
-A common example of redundant state is code like this:
+Un ejemplo común de estado redundante es un código como este:
```js
function Message({ messageColor }) {
const [color, setColor] = useState(messageColor);
```
-Here, a `color` state variable is initialized to the `messageColor` prop. The problem is that **if the parent component passes a different value of `messageColor` later (for example, `'red'` instead of `'blue'`), the `color` *state variable* would not be updated!** The state is only initialized during the first render.
+Aquí, una variable de estado `color` se inicializa en la prop `messageColor`. El problema es que **si el componente principal pasa un valor diferente de `messageColor` más adelante (por ejemplo, `'red'` en lugar de `'blue'`), ¡la *variable de estado* `color`¡no se actualizará!** el estado solo se inicializa durante el primer renderizado.
-This is why "mirroring" some prop in a state variable can lead to confusion. Instead, use the `messageColor` prop directly in your code. If you want to give it a shorter name, use a constant:
+Esta es la razón por la que "reflejar" alguna prop en una variable de estado puede generar confusión. En su lugar, usa el accesorio `messageColor` directamente en tu código. Si deseas darle un nombre más corto, use una constante:
```js
function Message({ messageColor }) {
const color = messageColor;
```
-This way it won't get out of sync with the prop passed from the parent component.
+De esta forma, no se sincroniza con la propiedad que se pasa desde el componente principal.
-"Mirroring" props into state only makes sense when you *want* to ignore all updates for a specific prop. By convention, start the prop name with `initial` or `default` to clarify that its new values are ignored:
+"Reflejar" props en estado solo tiene sentido cuando *quieres* ignorar todas las actualizaciones de una prop en específico. Por convención, comienza el nombre de la prop con `initial` or `default` para aclarar que sus nuevos valores se ignoran:
```js
function Message({ initialColor }) {
- // The `color` state variable holds the *first* value of `initialColor`.
- // Further changes to the `initialColor` prop are ignored.
+// La variable de estado `color` contiene el *primer* valor de `initialColor`.
+// Se ignoran los cambios posteriores a la prop `initialColor`.
const [color, setColor] = useState(initialColor);
```
-## Avoid duplication in state {/*avoid-duplication-in-state*/}
+## Evita la duplicación en el estado {/*avoid-duplication-in-state*/}
-This menu list component lets you choose a single travel snack out of several:
+Este componente de lista de menú te permite elegir un solo refrigerio de viaje entre varios:
@@ -398,7 +398,7 @@ export default function Menu() {
return (
<>
-
>
);
}
@@ -422,9 +422,9 @@ button { margin-top: 10px; }
-Currently, it stores the selected item as an object in the `selectedItem` state variable. However, this is not great: **the contents of the `selectedItem` is the same object as one of the items inside the `items` list.** This means that the information about the item itself is duplicated in two places.
+Actualmente, almacena el elemento seleccionado como un objeto en la variable de estado `selectedItem`. Sin embargo, esto no está bien: **el contenido de `selectedItem` es el mismo objeto que uno de los elementos dentro de la lista de `items`.** Esto significa que la información sobre el elemento en sí está duplicada en dos lugares.
-Why is this a problem? Let's make each item editable:
+¿Por qué es esto un problema? Hagamos que cada elemento sea editable:
@@ -458,7 +458,7 @@ export default function Menu() {
return (
<>
-
>
);
}
@@ -487,9 +487,9 @@ button { margin-top: 10px; }
-Notice how if you first click "Choose" on an item and *then* edit it, **the input updates but the label at the bottom does not reflect the edits.** This is because you have duplicated state, and you forgot to update `selectedItem`.
+Observe cómo si primero haces clic en "Seleccionar" en un elemento y *luego* lo editas, **la entrada se actualiza, pero la etiqueta en la parte inferior no refleja las ediciones.** Esto se debe a que tienes un estado duplicado y te olvidaste de actualizar `selectedItem`.
-Although you could update `selectedItem` too, an easier fix is to remove duplication. In this example, instead of a `selectedItem` object (which creates a duplication with objects inside `items`), you hold the `selectedId` in state, and *then* get the `selectedItem` by searching the `items` array for an item with that ID:
+Aunque también podría actualizar `selectedItem`, una solución más fácil es eliminar la duplicación. En este ejemplo, en lugar de un objeto `selectedItem` (que crea una duplicación con objetos dentro de `items`), mantienes `selectedId` en el estado, y *luego* obtienes el `selectedItem` buscando en la matriz `items` un artículo con esa identificación:
@@ -525,7 +525,7 @@ export default function Menu() {
return (
<>
-
>
);
}
@@ -554,25 +554,25 @@ button { margin-top: 10px; }
-(Alternatively, you may hold the selected index in state.)
+(Alternativamente, puedes mantener el índice seleccionado en el estado).
-The state used to be duplicated like this:
+El estado solía duplicarse de esta manera:
* `items = [{ id: 0, title: 'pretzels'}, ...]`
* `selectedItem = {id: 0, title: 'pretzels'}`
-But after the change it's like this:
+Pero después del cambio es así:
* `items = [{ id: 0, title: 'pretzels'}, ...]`
* `selectedId = 0`
-The duplication is gone, and you only keep the essential state!
+¡La duplicación se ha ido, y solo conservas el estado esencial!
-Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in state, because only the *selected ID* is essential. The rest could be calculated during render.
+Ahora, si editas el item *seleccionado*, el siguiente mensaje se actualizará inmediatamente. Esto se debe a que `setItems` desencadena una nueva representación, y `items.find(...)` encontraría el item con el título actualizado. No era necesario mantener *el item seleccionado* en el estado, porque solo el *ID seleccionado* es esencial. El resto podría calcularse durante el renderizado.
-## Avoid deeply nested state {/*avoid-deeply-nested-state*/}
+## Evita el estado profundamente anidado {/*avoid-deeply-nested-state*/}
-Imagine a travel plan consisting of planets, continents, and countries. You might be tempted to structure its state using nested objects and arrays, like in this example:
+Imagina un plan de viaje compuesto por planetas, continentes y países. Es posible que sientas la tentación de estructurar tu estado mediante objetos y matrices anidados, como en este ejemplo:
@@ -601,7 +601,7 @@ export default function TravelPlan() {
const planets = plan.childPlaces;
return (
<>
-
Places to visit
+
Lugares para visitar
{planets.map(place => (
@@ -618,7 +618,7 @@ export const initialTravelPlan = {
title: '(Root)',
childPlaces: [{
id: 1,
- title: 'Earth',
+ title: 'Tierra',
childPlaces: [{
id: 2,
title: 'Africa',
@@ -628,11 +628,11 @@ export const initialTravelPlan = {
childPlaces: []
}, {
id: 4,
- title: 'Egypt',
+ title: 'Egipto',
childPlaces: []
}, {
id: 5,
- title: 'Kenya',
+ title: 'Kenia',
childPlaces: []
}, {
id: 6,
@@ -640,7 +640,7 @@ export const initialTravelPlan = {
childPlaces: []
}, {
id: 7,
- title: 'Morocco',
+ title: 'Marruecos',
childPlaces: []
}, {
id: 8,
@@ -648,19 +648,19 @@ export const initialTravelPlan = {
childPlaces: []
}, {
id: 9,
- title: 'South Africa',
+ title: 'Sudafrica',
childPlaces: []
}]
}, {
id: 10,
- title: 'Americas',
+ title: 'Las Americas',
childPlaces: [{
id: 11,
title: 'Argentina',
childPlaces: []
}, {
id: 12,
- title: 'Brazil',
+ title: 'Brasil',
childPlaces: []
}, {
id: 13,
@@ -680,7 +680,7 @@ export const initialTravelPlan = {
childPlaces: []
}, {
id: 17,
- title: 'Trinidad and Tobago',
+ title: 'Trinidad y Tobago',
childPlaces: []
}, {
id: 18,
@@ -704,15 +704,15 @@ export const initialTravelPlan = {
childPlaces: []
}, {
id: 23,
- title: 'Singapore',
+ title: 'Singapur',
childPlaces: []
}, {
id: 24,
- title: 'South Korea',
+ title: 'Corea del sur',
childPlaces: []
}, {
id: 25,
- title: 'Thailand',
+ title: 'Tailandia',
childPlaces: []
}, {
id: 26,
@@ -721,22 +721,22 @@ export const initialTravelPlan = {
}]
}, {
id: 27,
- title: 'Europe',
+ title: 'Europa',
childPlaces: [{
id: 28,
- title: 'Croatia',
+ title: 'Croacia',
childPlaces: [],
}, {
id: 29,
- title: 'France',
+ title: 'Francia',
childPlaces: [],
}, {
id: 30,
- title: 'Germany',
+ title: 'Alemania',
childPlaces: [],
}, {
id: 31,
- title: 'Italy',
+ title: 'Italia',
childPlaces: [],
}, {
id: 32,
@@ -744,11 +744,11 @@ export const initialTravelPlan = {
childPlaces: [],
}, {
id: 33,
- title: 'Spain',
+ title: 'España',
childPlaces: [],
}, {
id: 34,
- title: 'Turkey',
+ title: 'Turquia',
childPlaces: [],
}]
}, {
@@ -760,11 +760,11 @@ export const initialTravelPlan = {
childPlaces: [],
}, {
id: 37,
- title: 'Bora Bora (French Polynesia)',
+ title: 'Bora Bora (Polinesia Franciasa)',
childPlaces: [],
}, {
id: 38,
- title: 'Easter Island (Chile)',
+ title: 'Isla de pascua (Chile)',
childPlaces: [],
}, {
id: 39,
@@ -772,11 +772,11 @@ export const initialTravelPlan = {
childPlaces: [],
}, {
id: 40,
- title: 'Hawaii (the USA)',
+ title: 'Hawaii (Estados Unidos)',
childPlaces: [],
}, {
id: 41,
- title: 'New Zealand',
+ title: 'Nueva Zelanda',
childPlaces: [],
}, {
id: 42,
@@ -786,23 +786,23 @@ export const initialTravelPlan = {
}]
}, {
id: 43,
- title: 'Moon',
+ title: 'Luna',
childPlaces: [{
id: 44,
- title: 'Rheita',
+ title: 'Rheita (cráter)',
childPlaces: []
}, {
id: 45,
- title: 'Piccolomini',
+ title: 'Piccolomini (cráter)',
childPlaces: []
}, {
id: 46,
- title: 'Tycho',
+ title: 'Tycho (cráter)',
childPlaces: []
}]
}, {
id: 47,
- title: 'Mars',
+ title: 'Marte',
childPlaces: [{
id: 48,
title: 'Corn Town',
@@ -810,7 +810,7 @@ export const initialTravelPlan = {
}, {
id: 49,
title: 'Green Hill',
- childPlaces: []
+ childPlaces: []
}]
}]
};
@@ -818,11 +818,11 @@ export const initialTravelPlan = {
-Now let's say you want to add a button to delete a place you've already visited. How would you go about it? [Updating nested state](/learn/updating-objects-in-state#updating-a-nested-object) involves making copies of objects all the way up from the part that changed. Deleting a deeply nested place would involve copying its entire parent place chain. Such code can be very verbose.
+Ahora, supongamos que deseas agregar un botón para eliminar un lugar que ya visitaste. ¿Cómo lo harías? [Actualizar el estado anidado](/learn/updating-objects-in-state#updating-a-nested-object) implica hacer copias de objetos desde la parte que cambió. La eliminación de un lugar profundamente anidado implica copiar toda la cadena de lugares principal. Dicho código puede ser muy detallado.
-**If the state is too nested to update easily, consider making it "flat".** Here is one way you can restructure this data. Instead of a tree-like structure where each `place` has an array of *its child places*, you can have each place hold an array of *its child place IDs*. Then you can store a mapping from each place ID to the corresponding place.
+**Si el estado está demasiado anidado para actualizarse fácilmente, considera hacerlo "plano".** Esta es una manera de reestructurar estos datos. En lugar de una estructura similar a un árbol donde cada `lugar` tiene una matriz de *sus lugares secundarios*, puedes hacer que cada lugar contenga una matriz de *sus ID de lugares secundarios*. Luego puedes almacenar un mapeo de cada ID de lugar al lugar correspondiente.
-This data restructuring might remind you of seeing a database table:
+Esta reestructuración de datos puede recordarte ver una tabla de base de datos:
@@ -857,7 +857,7 @@ export default function TravelPlan() {
const planetIds = root.childIds;
return (
<>
-
Places to visit
+
Lugares a visitar
{planetIds.map(id => (
-**Now that the state is "flat" (also known as "normalized"), updating nested items becomes easier.**
+**Ahora que el estado es "plano" (también conocido como "normalizado"), la actualización de elementos anidados se vuelve más fácil.**
-In order to remove a place now, you only need to update two levels of state:
+Para eliminar un lugar ahora, solo necesitas actualizar dos niveles de estado:
-- The updated version of its *parent* place should exclude the removed ID from its `childIds` array.
-- The updated version of the root "table" object should include the updated version of the parent place.
+* La versión actualizada de su lugar *principal* debería excluir el ID eliminado de su matriz `childIds`.
+* La versión actualizada del objeto raíz de "tabla" debe incluir la versión actualizada del lugar principal.
-Here is an example of how you could go about it:
+Este es un ejemplo de cómo podrías hacerlo:
@@ -1149,17 +1149,17 @@ export default function TravelPlan() {
function handleComplete(parentId, childId) {
const parent = plan[parentId];
- // Create a new version of the parent place
- // that doesn't include this child ID.
+ // Crear una nueva versión del lugar principal
+ // que no incluye ID del hijo.
const nextParent = {
...parent,
childIds: parent.childIds
.filter(id => id !== childId)
};
- // Update the root state object...
+ // Actualizar el objeto de estado raíz...
setPlan({
...plan,
- // ...so that it has the updated parent.
+ // ...para que tenga el padre este actualizado.
[parentId]: nextParent
});
}
@@ -1168,7 +1168,7 @@ export default function TravelPlan() {
const planetIds = root.childIds;
return (
<>
-
Places to visit
+
Logares a visitar
{planetIds.map(id => (
{
onComplete(parentId, id);
}}>
- Complete
+ Completado
{childIds.length > 0 &&
@@ -1222,14 +1222,14 @@ export const initialTravelPlan = {
},
1: {
id: 1,
- title: 'Earth',
+ title: 'Tierra',
childIds: [2, 10, 19, 27, 35]
},
2: {
id: 2,
title: 'Africa',
childIds: [3, 4, 5, 6 , 7, 8, 9]
- },
+ },
3: {
id: 3,
title: 'Botswana',
@@ -1237,22 +1237,22 @@ export const initialTravelPlan = {
},
4: {
id: 4,
- title: 'Egypt',
+ title: 'Egipto',
childIds: []
},
5: {
id: 5,
- title: 'Kenya',
+ title: 'Kenia',
childIds: []
},
6: {
id: 6,
title: 'Madagascar',
childIds: []
- },
+ },
7: {
id: 7,
- title: 'Morocco',
+ title: 'Marruecos',
childIds: []
},
8: {
@@ -1262,13 +1262,13 @@ export const initialTravelPlan = {
},
9: {
id: 9,
- title: 'South Africa',
+ title: 'Sudafrica',
childIds: []
},
10: {
id: 10,
- title: 'Americas',
- childIds: [11, 12, 13, 14, 15, 16, 17, 18],
+ title: 'Las Americas',
+ childIds: [11, 12, 13, 14, 15, 16, 17, 18],
},
11: {
id: 11,
@@ -1277,14 +1277,14 @@ export const initialTravelPlan = {
},
12: {
id: 12,
- title: 'Brazil',
+ title: 'Brasil',
childIds: []
},
13: {
id: 13,
title: 'Barbados',
childIds: []
- },
+ },
14: {
id: 14,
title: 'Canada',
@@ -1302,7 +1302,7 @@ export const initialTravelPlan = {
},
17: {
id: 17,
- title: 'Trinidad and Tobago',
+ title: 'Trinidad y Tobago',
childIds: []
},
18: {
@@ -1313,7 +1313,7 @@ export const initialTravelPlan = {
19: {
id: 19,
title: 'Asia',
- childIds: [20, 21, 22, 23, 24, 25, 26],
+ childIds: [20, 21, 22, 23, 24, 25, 26],
},
20: {
id: 20,
@@ -1332,17 +1332,17 @@ export const initialTravelPlan = {
},
23: {
id: 23,
- title: 'Singapore',
+ title: 'Singapur',
childIds: []
},
24: {
id: 24,
- title: 'South Korea',
+ title: 'Corea del norte',
childIds: []
},
25: {
id: 25,
- title: 'Thailand',
+ title: 'Tailandia',
childIds: []
},
26: {
@@ -1352,27 +1352,27 @@ export const initialTravelPlan = {
},
27: {
id: 27,
- title: 'Europe',
- childIds: [28, 29, 30, 31, 32, 33, 34],
+ title: 'Europa',
+ childIds: [28, 29, 30, 31, 32, 33, 34],
},
28: {
id: 28,
- title: 'Croatia',
+ title: 'Croacia',
childIds: []
},
29: {
id: 29,
- title: 'France',
+ title: 'Francia',
childIds: []
},
30: {
id: 30,
- title: 'Germany',
+ title: 'Alemania',
childIds: []
},
31: {
id: 31,
- title: 'Italy',
+ title: 'Italia',
childIds: []
},
32: {
@@ -1382,18 +1382,18 @@ export const initialTravelPlan = {
},
33: {
id: 33,
- title: 'Spain',
+ title: 'España',
childIds: []
},
34: {
id: 34,
- title: 'Turkey',
+ title: 'Turquia',
childIds: []
},
35: {
id: 35,
title: 'Oceania',
- childIds: [36, 37, 38, 39, 40, 41,, 42],
+ childIds: [36, 37, 38, 39, 40, 41,, 42],
},
36: {
id: 36,
@@ -1402,12 +1402,12 @@ export const initialTravelPlan = {
},
37: {
id: 37,
- title: 'Bora Bora (French Polynesia)',
+ title: 'Bora Bora (Polinesia Francesa)',
childIds: []
},
38: {
id: 38,
- title: 'Easter Island (Chile)',
+ title: 'Isla de Pascua (Chile)',
childIds: []
},
39: {
@@ -1417,12 +1417,12 @@ export const initialTravelPlan = {
},
40: {
id: 40,
- title: 'Hawaii (the USA)',
+ title: 'Hawaii (Estados Unidos)',
childIds: []
},
41: {
id: 41,
- title: 'New Zealand',
+ title: 'Nueva Zelanda',
childIds: []
},
42: {
@@ -1432,27 +1432,27 @@ export const initialTravelPlan = {
},
43: {
id: 43,
- title: 'Moon',
+ title: 'Luna',
childIds: [44, 45, 46]
},
44: {
id: 44,
- title: 'Rheita',
+ title: 'Rheita (cráter)',
childIds: []
},
45: {
id: 45,
- title: 'Piccolomini',
+ title: 'Piccolomini (cráter)',
childIds: []
},
46: {
id: 46,
- title: 'Tycho',
+ title: 'Tycho (cráter)',
childIds: []
},
47: {
id: 47,
- title: 'Mars',
+ title: 'Marte',
childIds: [48, 49]
},
48: {
@@ -1474,13 +1474,13 @@ button { margin: 10px; }
-You can nest state as much as you like, but making it "flat" can solve numerous problems. It makes state easier to update, and it helps ensure you don't have duplication in different parts of a nested object.
+Puede anidar el estado tanto como desees, pero hacerlo "plano" puede resolver numerosos problemas. Facilita la actualización del estado y ayuda a garantizar que no haya duplicación en diferentes partes de un objeto anidado.
-#### Improving memory usage {/*improving-memory-usage*/}
+#### Mejorar el uso de memoria {/*improving-memory-usage*/}
-Ideally, you would also remove the deleted items (and their children!) from the "table" object to improve memory usage. This version does that. It also [uses Immer](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) to make the update logic more concise.
+Idealmente, también eliminaría los elementos eliminados (¡y sus hijos!) del objeto "tabla" para mejorar el uso de la memoria. Esta versión lo hace. También [usa Immer](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) para hacer que la lógica de actualización sea más concisa.
@@ -1493,12 +1493,12 @@ export default function TravelPlan() {
function handleComplete(parentId, childId) {
updatePlan(draft => {
- // Remove from the parent place's child IDs.
+ // Elimina los ID secundarios del lugar principal.
const parent = draft[parentId];
parent.childIds = parent.childIds
.filter(id => id !== childId);
- // Forget this place and all its subtree.
+ // Olvida este lugar y todo su subárbol.
deleteAllChildren(childId);
function deleteAllChildren(id) {
const place = draft[id];
@@ -1512,7 +1512,7 @@ export default function TravelPlan() {
const planetIds = root.childIds;
return (
<>
-
Places to visit
+
Lugares a visitar
{planetIds.map(id => (
{
onComplete(parentId, id);
}}>
- Complete
+ Completado
{childIds.length > 0 &&
@@ -1566,14 +1566,14 @@ export const initialTravelPlan = {
},
1: {
id: 1,
- title: 'Earth',
+ title: 'Tierra',
childIds: [2, 10, 19, 27, 35]
},
2: {
id: 2,
title: 'Africa',
childIds: [3, 4, 5, 6 , 7, 8, 9]
- },
+ },
3: {
id: 3,
title: 'Botswana',
@@ -1581,22 +1581,22 @@ export const initialTravelPlan = {
},
4: {
id: 4,
- title: 'Egypt',
+ title: 'Egipto',
childIds: []
},
5: {
id: 5,
- title: 'Kenya',
+ title: 'Kenia',
childIds: []
},
6: {
id: 6,
title: 'Madagascar',
childIds: []
- },
+ },
7: {
id: 7,
- title: 'Morocco',
+ title: 'Marruecos',
childIds: []
},
8: {
@@ -1606,13 +1606,13 @@ export const initialTravelPlan = {
},
9: {
id: 9,
- title: 'South Africa',
+ title: 'Sudafrica',
childIds: []
},
10: {
id: 10,
- title: 'Americas',
- childIds: [11, 12, 13, 14, 15, 16, 17, 18],
+ title: 'Las Americas',
+ childIds: [11, 12, 13, 14, 15, 16, 17, 18],
},
11: {
id: 11,
@@ -1621,14 +1621,14 @@ export const initialTravelPlan = {
},
12: {
id: 12,
- title: 'Brazil',
+ title: 'Brasil',
childIds: []
},
13: {
id: 13,
title: 'Barbados',
childIds: []
- },
+ },
14: {
id: 14,
title: 'Canada',
@@ -1646,7 +1646,7 @@ export const initialTravelPlan = {
},
17: {
id: 17,
- title: 'Trinidad and Tobago',
+ title: 'Trinidad y Tobago',
childIds: []
},
18: {
@@ -1657,7 +1657,7 @@ export const initialTravelPlan = {
19: {
id: 19,
title: 'Asia',
- childIds: [20, 21, 22, 23, 24, 25, 26],
+ childIds: [20, 21, 22, 23, 24, 25, 26],
},
20: {
id: 20,
@@ -1676,17 +1676,17 @@ export const initialTravelPlan = {
},
23: {
id: 23,
- title: 'Singapore',
+ title: 'Singapur',
childIds: []
},
24: {
id: 24,
- title: 'South Korea',
+ title: 'Corea del norte',
childIds: []
},
25: {
id: 25,
- title: 'Thailand',
+ title: 'Tailandia',
childIds: []
},
26: {
@@ -1696,27 +1696,27 @@ export const initialTravelPlan = {
},
27: {
id: 27,
- title: 'Europe',
- childIds: [28, 29, 30, 31, 32, 33, 34],
+ title: 'Europa',
+ childIds: [28, 29, 30, 31, 32, 33, 34],
},
28: {
id: 28,
- title: 'Croatia',
+ title: 'Croacia',
childIds: []
},
29: {
id: 29,
- title: 'France',
+ title: 'Francia',
childIds: []
},
30: {
id: 30,
- title: 'Germany',
+ title: 'Alemania',
childIds: []
},
31: {
id: 31,
- title: 'Italy',
+ title: 'Italia',
childIds: []
},
32: {
@@ -1726,18 +1726,18 @@ export const initialTravelPlan = {
},
33: {
id: 33,
- title: 'Spain',
+ title: 'España',
childIds: []
},
34: {
id: 34,
- title: 'Turkey',
+ title: 'Turquia',
childIds: []
},
35: {
id: 35,
title: 'Oceania',
- childIds: [36, 37, 38, 39, 40, 41,, 42],
+ childIds: [36, 37, 38, 39, 40, 41,, 42],
},
36: {
id: 36,
@@ -1746,12 +1746,12 @@ export const initialTravelPlan = {
},
37: {
id: 37,
- title: 'Bora Bora (French Polynesia)',
+ title: 'Bora Bora (Polinesia Francesa)',
childIds: []
},
38: {
id: 38,
- title: 'Easter Island (Chile)',
+ title: 'Isla de Pascua (Chile)',
childIds: []
},
39: {
@@ -1761,12 +1761,12 @@ export const initialTravelPlan = {
},
40: {
id: 40,
- title: 'Hawaii (the USA)',
+ title: 'Hawaii (Estados Unidos)',
childIds: []
},
41: {
id: 41,
- title: 'New Zealand',
+ title: 'Nueva Zelanda',
childIds: []
},
42: {
@@ -1776,27 +1776,27 @@ export const initialTravelPlan = {
},
43: {
id: 43,
- title: 'Moon',
+ title: 'Luna',
childIds: [44, 45, 46]
},
44: {
id: 44,
- title: 'Rheita',
+ title: 'Rheita (cráter)',
childIds: []
},
45: {
id: 45,
- title: 'Piccolomini',
+ title: 'Piccolomini (cráter)',
childIds: []
},
46: {
id: 46,
- title: 'Tycho',
+ title: 'Tycho (cráter)',
childIds: []
},
47: {
id: 47,
- title: 'Mars',
+ title: 'Marte',
childIds: [48, 49]
},
48: {
@@ -1838,25 +1838,25 @@ button { margin: 10px; }
-Sometimes, you can also reduce state nesting by moving some of the nested state into the child components. This works well for ephemeral UI state that doesn't need to be stored, like whether an item is hovered.
+A veces, también puedes reducir el anidamiento de estados moviendo algunos de los estados anidados a los componentes secundarios. Esto funciona bien para el estado efímero de la interfaz de usuario que no necesita almacenarse, por ejemplo, si se pasa el cursor por encima de un elemento.
-* If two state variables always update together, consider merging them into one.
-* Choose your state variables carefully to avoid creating "impossible" states.
-* Structure your state in a way that reduces the chances that you'll make a mistake updating it.
-* Avoid redundant and duplicate state so that you don't need to keep it in sync.
-* Don't put props *into* state unless you specifically want to prevent updates.
-* For UI patterns like selection, keep ID or index in state instead of the object itself.
-* If updating deeply nested state is complicated, try flattening it.
+* Si dos variables de estado siempre se actualizan juntas, considera combinarlas en una.
+* Elige cuidadosamente tus variables de estado para evitar crear estados "imposibles".
+* Estructura tu estado de una manera que reduzca las posibilidades de que cometas un error al actualizarlo.
+* Evita el estado redundante y duplicado para que no necesites mantenerlo sincronizado.
+* No pongas props *en* estado a menos que desees evitar específicamente las actualizaciones.
+* Para patrones de interfaz de usuario como la selección, mantén el ID o el índice en estado en lugar del objeto mismo.
+* Si actualizar el estado profundamente anidado es complicado, intenta aplanarlo.
-#### Fix a component that's not updating {/*fix-a-component-thats-not-updating*/}
+#### Arreglar un componente que no se actualiza {/*fix-a-component-thats-not-updating*/}
-This `Clock` component receives two props: `color` and `time`. When you select a different color in the select box, the `Clock` component receives a different `color` prop from its parent component. However, for some reason, the displayed color doesn't update. Why? Fix the problem.
+Este componente `Reloj` recibe dos props: `color` y `tiempo`. Cuando seleccionas un color diferente en el cuadro de selección, el componente `Reloj` recibe una prop de `color` diferente de su componente principal. Sin embargo, por alguna razón, el color mostrado no se actualiza. ¿Por qué? Arregla el problema.
@@ -1894,7 +1894,7 @@ export default function App() {
return (