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 (
-

How was your stay at The Prancing Pony?

+

¿Cómo fue tu estadía en The Prancing Pony?