diff --git a/beta/src/content/learn/updating-objects-in-state.md b/beta/src/content/learn/updating-objects-in-state.md
index d461f117b..30571257b 100644
--- a/beta/src/content/learn/updating-objects-in-state.md
+++ b/beta/src/content/learn/updating-objects-in-state.md
@@ -1,57 +1,57 @@
---
-title: Updating Objects in State
+title: Actualizar objetos en el estado
---
-State can hold any kind of JavaScript value, including objects. But you shouldn't change objects that you hold in the React state directly. Instead, when you want to update an object, you need to create a new one (or make a copy of an existing one), and then set the state to use that copy.
+El estado puede contener cualquier tipo de valor JavaScript, incluyendo objetos. Pero no deberías cambiar los objetos que tienes en el estado de React directamente. En su lugar, cuando quieras actualizar un objeto, tienes que crear uno nuevo (o hacer una copia de uno existente), y luego configurar el estado para usar esa copia.
-- How to correctly update an object in React state
-- How to update a nested object without mutating it
-- What immutability is, and how not to break it
-- How to make object copying less repetitive with Immer
+- Cómo actualizar correctamente un objeto en el estado de React
+- Cómo actualizar un objeto anidado sin mutarlo
+- Qué es la inmutabilidad y cómo no romperla
+- Cómo hacer que la copia de objetos sea menos repetitiva con Immer
-## What's a mutation? {/*whats-a-mutation*/}
+## ¿Qué es una mutación? {/*whats-a-mutation*/}
-You can store any kind of JavaScript value in state.
+Puede almacenar cualquier tipo de valor de JavaScript en el estado.
```js
const [x, setX] = useState(0);
```
-So far you've been working with numbers, strings, and booleans. These kinds of JavaScript values are "immutable", meaning unchangeable or "read-only". You can trigger a re-render to _replace_ a value:
+Hasta ahora has trabajado con números, _strings_ y booleanos. Estos tipos de valores de JavaScript son "inmutables", es decir, inmutables o de "sólo lectura". Se puede activar un re-renderizado para _reemplazar_ un valor:
```js
setX(5);
```
-The `x` state changed from `0` to `5`, but the _number `0` itself_ did not change. It's not possible to make any changes to the built-in primitive values like numbers, strings, and booleans in JavaScript.
+El estado `x` ha cambiado de `0` a `5`, pero el _número `0` en sí mismo_ no cambia. No es posible hacer ningún cambio en los valores primitivos incorporados como números, _strings_ y booleanos en JavaScript.
-Now consider an object in state:
+Consideremos ahora un objeto en estado:
```js
const [position, setPosition] = useState({ x: 0, y: 0 });
```
-Technically, it is possible to change the contents of _the object itself_. **This is called a mutation:**
+Técnicamente, es posible cambiar el contenido del _objeto mismo_. **Esto se denomina mutación:**.
```js
position.x = 5;
```
-However, although objects in React state are technically mutable, you should treat them **as if** they were immutable--like numbers, booleans, and strings. Instead of mutating them, you should always replace them.
+Sin embargo, aunque los objetos en el estado de React son técnicamente mutables, deberías tratarlos **como si** fueran inmutables--como los números, booleanos y _strings_. En lugar de mutarlos, siempre debes reemplazarlos.
-## Treat state as read-only {/*treat-state-as-read-only*/}
+## Tratar el estado como de sólo lectura {/*treat-state-as-read-only*/}
-In other words, you should **treat any JavaScript object that you put into state as read-only.**
+En otras palabras, debes **tratar cualquier objeto JavaScript que pongas en estado como de sólo lectura.**
-This example holds an object in state to represent the current pointer position. The red dot is supposed to move when you touch or move the cursor over the preview area. But the dot stays in the initial position:
+Este ejemplo mantiene un objeto en el estado para representar la posición actual del puntero. Se supone que el punto rojo se mueve cuando se toca o se mueve el cursor, sobre el área de vista previa. Pero el punto permanece en la posición inicial:
@@ -94,7 +94,7 @@ body { margin: 0; padding: 0; height: 250px; }
-The problem is with this bit of code.
+El problema está en este trozo de código.
```js
onPointerMove={e => {
@@ -103,9 +103,9 @@ onPointerMove={e => {
}}
```
-This code modifies the object assigned to `position` from [the previous render.](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) But without using the state setting function, React has no idea that object has changed. So React does not do anything in response. It's like trying to change the order after you've already eaten the meal. While mutating state can work in some cases, we don't recommend it. You should treat the state value you have access to in a render as read-only.
+Este código modifica el objeto asignado a `position` desde [el renderizado anterior.](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) Pero sin usar la función de ajuste de estado, React no tiene idea de que el objeto ha cambiado. Así que React no hace nada en respuesta. Es como intentar cambiar el orden de lo que has comido cuando ya has acabado. Aunque mutar el estado puede funcionar en algunos casos, no lo recomendamos. Debes tratar el valor del estado al que tienes acceso en un renderizado como de sólo lectura.
-To actually [trigger a re-render](/learn/state-as-a-snapshot#setting-state-triggers-renders) in this case, **create a *new* object and pass it to the state setting function:**
+Para realmente [conseguir un re-renderizado](/learn/state-as-a-snapshot#setting-state-triggers-renders) en este caso, **crea un objeto *nuevo* y pásalo a la función de configuración de estado:**
```js
onPointerMove={e => {
@@ -116,12 +116,12 @@ onPointerMove={e => {
}}
```
-With `setPosition`, you're telling React:
+Con `setPosition`, le estás diciendo a React:
-* Replace `position` with this new object
-* And render this component again
+* Reemplaza `position` con este nuevo objeto
+* Y renderiza este componente de nuevo
-Notice how the red dot now follows your pointer when you touch or hover over the preview area:
+Observa cómo el punto rojo sigue ahora a tu puntero cuando tocas o pasas el ratón por encima del área de vista previa:
@@ -166,16 +166,16 @@ body { margin: 0; padding: 0; height: 250px; }
-
+
-Code like this is a problem because it modifies an *existing* object in state:
+Un código como este es un problema porque modifica un objeto *existente* en el estado:
```js
position.x = e.clientX;
position.y = e.clientY;
```
-But code like this is **absolutely fine** because you're mutating a fresh object you have *just created*:
+Pero un código como el siguiente está **absolutamente bien**, ya que estarías mutando un objeto que *acabas de crear*:
```js
const nextPosition = {};
@@ -184,7 +184,7 @@ nextPosition.y = e.clientY;
setPosition(nextPosition);
````
-In fact, it is completely equivalent to writing this:
+De hecho, es completamente equivalente a escribir lo siguiente:
```js
setPosition({
@@ -193,15 +193,15 @@ setPosition({
});
```
-Mutation is only a problem when you change *existing* objects that are already in state. Mutating an object you've just created is okay because *no other code references it yet.* Changing it isn't going to accidentally impact something that depends on it. This is called a "local mutation". You can even do local mutation [while rendering.](/learn/keeping-components-pure#local-mutation-your-components-little-secret) Very convenient and completely okay!
+La mutación sólo es un problema cuando cambias objetos *existentes* que ya están en el estado. Mutar un objeto que acabas de crear está bien porque *ningún otro código hace referencia a él todavía.* Cambiarlo no va a afectar accidentalmente a algo que dependa de él. Esto se llama "mutación local". Incluso puedes hacer una mutación local [mientras renderizas.](/learn/keeping-components-pure#local-mutation-your-components-little-secret) ¡Muy conveniente y completamente bien!
-## Copying objects with the spread syntax {/*copying-objects-with-the-spread-syntax*/}
+## Copiar objetos con la sintaxis extendida {/*copying-objects-with-the-spread-syntax*/}
-In the previous example, the `position` object is always created fresh from the current cursor position. But often, you will want to include *existing* data as a part of the new object you're creating. For example, you may want to update *only one* field in a form, but keep the previous values for all other fields.
+En el ejemplo anterior, el objeto `position` se crea siempre de nuevo a partir de la posición actual del cursor. Pero a menudo, querrás incluir datos *existentes* como parte del nuevo objeto que estás creando. Por ejemplo, puedes querer actualizar *sólo un* campo de un formulario, pero mantener los valores anteriores de todos los demás campos.
-These input fields don't work because the `onChange` handlers mutate the state:
+Estos campos de entrada no funcionan porque los manejadores `onChange` mutan el estado:
@@ -267,13 +267,13 @@ input { margin-left: 5px; margin-bottom: 5px; }
-For example, this line mutates the state from a past render:
+Por ejemplo, esta línea muta el estado de un render pasado:
```js
person.firstName = e.target.value;
```
-The reliable way to get the behavior you're looking for is to create a new object and pass it to `setPerson`. But here, you want to also **copy the existing data into it** because only one of the fields has changed:
+La forma fiable de obtener el comportamiento que buscas es crear un nuevo objeto y pasarlo a `setPerson`. Pero aquí, quieres también **copiar los datos existentes en él** porque sólo uno de los campos ha cambiado:
```js
setPerson({
@@ -283,7 +283,7 @@ setPerson({
});
```
-You can use the `...` [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals) syntax so that you don't need to copy every property separately.
+Se puede utilizar el `...` [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals) para no tener que copiar cada propiedad por separado.
```js
setPerson({
@@ -292,9 +292,9 @@ setPerson({
});
```
-Now the form works!
+¡Ahora el formulario funciona!
-Notice how you didn't declare a separate state variable for each input field. For large forms, keeping all data grouped in an object is very convenient--as long as you update it correctly!
+Fíjate en que no has declarado una variable de estado distinta para cada campo de entrada. Para los formularios grandes, es muy conveniente mantener todos los datos agrupados - ¡siempre y cuando los actualices correctamente!
@@ -369,11 +369,11 @@ input { margin-left: 5px; margin-bottom: 5px; }
-Note that the `...` spread syntax is "shallow"--it only copies things one level deep. This makes it fast, but it also means that if you want to update a nested property, you'll have to use it more than once.
+Ten en cuenta que la sintaxis extendida `...` es "superficial": sólo copia las cosas a un nivel de profundidad. Esto lo hace rápido, pero también significa que si quieres actualizar una propiedad anidada, tendrás que usarla más de una vez.
-
+
-You can also use the `[` and `]` braces inside your object definition to specify a property with dynamic name. Here is the same example, but with a single event handler instead of three different ones:
+También puedes utilizar las llaves `[` y `]` dentro de tu definición de objeto para especificar una propiedad con nombre dinámico. Aquí está el mismo ejemplo, pero con un solo manejador de eventos en lugar de tres diferentes:
@@ -437,13 +437,13 @@ input { margin-left: 5px; margin-bottom: 5px; }
-Here, `e.target.name` refers to the `name` property given to the `` DOM element.
+Aquí, `e.target.name` se refiere a la propiedad `name` dada al elemento DOM ``.
-## Updating a nested object {/*updating-a-nested-object*/}
+## Actualizar un objeto anidado {/*updating-a-nested-object*/}
-Consider a nested object structure like this:
+Considera una estructura de objetos anidados como esta:
```js
const [person, setPerson] = useState({
@@ -456,13 +456,13 @@ const [person, setPerson] = useState({
});
```
-If you wanted to update `person.artwork.city`, it's clear how to do it with mutation:
+Si quisieras actualizar `person.artwork.city`, está claro cómo hacerlo con la mutación:
```js
person.artwork.city = 'New Delhi';
```
-But in React, you treat state as immutable! In order to change `city`, you would first need to produce the new `artwork` object (pre-populated with data from the previous one), and then produce the new `person` object which points at the new `artwork`:
+Pero en React, ¡se trata el estado como inmutable! Para cambiar la "ciudad", primero tendrías que producir el nuevo objeto "artwork" (pre-poblado con los datos de la anterior), y luego producir el nuevo objeto "person" que apunta a la nueva "artwork":
```js
const nextArtwork = { ...person.artwork, city: 'New Delhi' };
@@ -470,7 +470,7 @@ const nextPerson = { ...person, artwork: nextArtwork };
setPerson(nextPerson);
```
-Or, written as a single function call:
+O, escrito como una sola llamada a la función:
```js
setPerson({
@@ -482,7 +482,7 @@ setPerson({
});
```
-This gets a bit wordy, but it works fine for many cases:
+Esto es un poco complicado, pero funciona bien para muchos casos:
@@ -590,9 +590,9 @@ img { width: 200px; height: 200px; }
-
+
-An object like this appears "nested" in code:
+Un objeto de este tipo aparece "anidado" en el código:
```js
let obj = {
@@ -605,7 +605,7 @@ let obj = {
};
```
-However, "nesting" is an inaccurate way to think about how objects behave. When the code executes, there is no such thing as a "nested" object. You are really looking at two different objects:
+Sin embargo, la "anidación" es una forma inexacta de pensar en el comportamiento de los objetos. Cuando el código se ejecuta, no existe tal cosa como un objeto "anidado". En realidad, se trata de dos objetos diferentes:
```js
let obj1 = {
@@ -620,7 +620,7 @@ let obj2 = {
};
```
-The `obj1` object is not "inside" `obj2`. For example, `obj3` could "point" at `obj1` too:
+El objeto `obj1` no está "dentro" de `obj2`. Por ejemplo, `obj3` también podría "apuntar" a `obj1`:
```js
let obj1 = {
@@ -640,13 +640,13 @@ let obj3 = {
};
```
-If you were to mutate `obj3.artwork.city`, it would affect both `obj2.artwork.city` and `obj1.city`. This is because `obj3.artwork`, `obj2.artwork`, and `obj1` are the same object. This is difficult to see when you think of objects as "nested". Instead, they are separate objects "pointing" at each other with properties.
+Si se muta `obj3.artwork.city`, afectaría tanto a `obj2.artwork.city` como a `obj1.city`. Esto se debe a que `obj3.artwork`, `obj2.artwork` y `obj1` son el mismo objeto. Esto es difícil de ver cuando se piensa en los objetos como "anidados". En cambio, son objetos separados que se "apuntan" unos a otros con propiedades.
-### Write concise update logic with Immer {/*write-concise-update-logic-with-immer*/}
+### Escribe una lógica de actualización concisa con Immer {/*write-concise-update-logic-with-immer*/}
-If your state is deeply nested, you might want to consider [flattening it.](/learn/choosing-the-state-structure#avoid-deeply-nested-state) But, if you don't want to change your state structure, you might prefer a shortcut to nested spreads. [Immer](https://github.com/immerjs/use-immer) is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object:
+Si su estado está profundamente anidado, podría considerar [aplanarlo.](/learn/choosing-the-state-structure#avoid-deeply-nested-state) Pero, si no quieres cambiar la estructura de tu estado, puede que prefieras un atajo a los spreads anidados. [Immer](https://github.com/immerjs/use-immer) es una popular librería que te permite escribir utilizando la sintaxis conveniente pero mutante y se encarga de producir las copias por ti. Con Immer, el código que escribes parece que estés "rompiendo las reglas" y mutando un objeto:
```js
updatePerson(draft => {
@@ -654,21 +654,21 @@ updatePerson(draft => {
});
```
-But unlike a regular mutation, it doesn't overwrite the past state!
+Pero a diferencia de una mutación normal, ¡no sobrescribe el estado anterior!
-
+
-The `draft` provided by Immer is a special type of object, called a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), that "records" what you do with it. This is why you can mutate it freely as much as you like! Under the hood, Immer figures out which parts of the `draft` have been changed, and produces a completely new object that contains your edits.
+El borrador (`draft`) proporcionado por Immer es un tipo especial de objeto, llamado [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), que "registra" lo que haces con él. Por eso, ¡puedes mutar libremente todo lo que quieras! Bajo el capó, Immer se da cuenta de qué partes del "borrador" han sido cambiadas, y produce un objeto completamente nuevo que contiene tus ediciones.
-To try Immer:
+Para probar Immer:
-1. Add `use-immer` to your `package.json` as a dependency
-2. Run `npm install`
-3. Then replace `import { useState } from 'react'` with `import { useImmer } from 'use-immer'`
+1. Añade `use-immer` a tu `package.json` como dependencia
+2. Ejecuta `npm install`.
+3. Luego sustituye `import { useState } de 'react'` por `import { useImmer } de 'use-immer'`.
-Here is the above example converted to Immer:
+Aquí está el ejemplo anterior convertido a Immer:
@@ -781,31 +781,31 @@ img { width: 200px; height: 200px; }
-Notice how much more concise the event handlers have become. You can mix and match `useState` and `useImmer` in a single component as much as you like. Immer is a great way to keep the update handlers concise, especially if there's nesting in your state, and copying objects leads to repetitive code.
+Fíjate en lo mucho más concisos que se han vuelto los manejadores de eventos. Puedes mezclar y combinar `useState` y `useImmer` en un mismo componente tanto como quieras. Immer es una gran manera de mantener los manejadores de actualización de manera concisa, especialmente si hay anidación en su estado, y la copia de objetos conduce a código repetitivo.
-
+
-There are a few reasons:
+Hay algunas razones:
-* **Debugging:** If you use `console.log` and don't mutate state, your past logs won't get clobbered by the more recent state changes. So you can clearly see how state has changed between renders.
-* **Optimizations:** Common React [optimization strategies](/apis/react/memo) rely on skipping work if previous props or state are the same as the next ones. If you never mutate state, it is very fast to check whether there were any changes. If `prevObj === obj`, you can be sure that nothing could have changed inside of it.
-* **New Features:** The new React features we're building rely on state being [treated like a snapshot.](/learn/state-as-a-snapshot) If you're mutating past versions of state, that may prevent you from using the new features.
-* **Requirement Changes:** Some application features, like implementing Undo/Redo, showing a history of changes, or letting the user reset a form to earlier values, are easier to do when nothing is mutated. This is because you can keep past copies of state in memory, and reuse them when appropriate. If you start with a mutative approach, features like this can be difficult to add later on.
-* **Simpler Implementation:** Because React does not rely on mutation, it does not need to do anything special with your objects. It does not need to hijack their properties, always wrap them into Proxies, or do other work at initialization as many "reactive" solutions do. This is also why React lets you put any object into state--no matter how large--without additional performance or correctness pitfalls.
+* **Debugging:** Si usas `console.log` y no mutas el estado, tus registros anteriores no se verán afectados por los cambios de estado más recientes. Así puedes ver claramente cómo ha cambiado el estado entre renders.
+* **Optimizaciones:** Las [estrategias de optimización](/apis/react/memo) más comunes en React se basan en ahorrar trabajo si las props o el estado anteriores son los mismos que los siguientes. Si nunca se muta el estado, es muy rápido comprobar si ha habido algún cambio. Si `prevObj === obj`, puedes estar seguro de que nada ha podido cambiar en su interior.
+* **Nuevas características:** Las nuevas características de React que estamos construyendo dependen de que el estado sea [tratado como una instantánea.](/learn/state-as-a-snapshot) Si estás mutando versiones anteriores del estado, eso puede impedirte utilizar las nuevas funciones.
+* **Cambios de requisitos:** Algunas características de la aplicación, como la implementación de Deshacer/Rehacer, mostrar un historial de cambios, o permitir al usuario restablecer un formulario a valores anteriores, son más fáciles de hacer cuando no se muta nada. Esto se debe a que puedes mantener copias pasadas del estado en la memoria, y reutilizarlas cuando sea apropiado. Si empiezas con un enfoque mutativo, características como estas pueden ser difíciles de añadir más adelante.
+* **Implementación más sencilla:** Como React no se basa en la mutación, no necesita hacer nada especial con tus objetos. No necesita apropiarse de sus propiedades, envolverlos siempre en Proxies, o hacer otro trabajo en la inicialización como hacen muchas soluciones "reactivas". Esta es también la razón por la que React te permite poner cualquier objeto en el estado - no importa lo grande que sea - sin problemas adicionales de rendimiento o corrección.
-In practice, you can often "get away" with mutating state in React, but we strongly advise you not to do that so that you can use new React features developed with this approach in mind. Future contributors and perhaps even your future self will thank you!
+En la práctica, a menudo puedes "salirte con la tuya" con la mutación de estado en React, pero te aconsejamos encarecidamente que no lo hagas para que puedas utilizar las nuevas características de React desarrolladas con este enfoque en mente. Los futuros colaboradores y quizás incluso tú mismo en el futuro te lo agradecerán.
-* Treat all state in React as immutable.
-* When you store objects in state, mutating them will not trigger renders and will change the state in previous render "snapshots".
-* Instead of mutating an object, create a *new* version of it, and trigger a re-render by setting state to it.
-* You can use the `{...obj, something: 'newValue'}` object spread syntax to create copies of objects.
-* Spread syntax is shallow: it only copies one level deep.
-* To update a nested object, you need to create copies all the way up from the place you're updating.
-* To reduce repetitive copying code, use Immer.
+* Tratar todo el estado en React como inmutable.
+* Cuando se almacenan objetos en el estado, la mutación de los mismos no desencadenará renderizados y cambiará el estado en las "instantáneas" de los renderizados anteriores.
+* En lugar de mutar un objeto, crea una *nueva* versión del mismo, y dispara un re-renderizado estableciendo el estado en él.
+* Puedes usar la sintaxis extendida de objetos `{...obj, algo: 'newValue'}` para crear copias de objetos.
+* La sintaxis extendida es superficial: sólo copia un nivel de profundidad.
+* Para actualizar un objeto anidado, necesitas crear copias desde el lugar que estás actualizando.
+* Para reducir el código de copia repetitivo, utiliza Immer.
@@ -813,11 +813,11 @@ In practice, you can often "get away" with mutating state in React, but we stron
-#### Fix incorrect state updates {/*fix-incorrect-state-updates*/}
+#### Corregir las actualizaciones de estado incorrectas {/*fix-incorrect-state-updates*/}
-This form has a few bugs. Click the button that increases the score a few times. Notice that it does not increase. Then edit the first name, and notice that the score has suddenly "caught up" with your changes. Finally, edit the last name, and notice that the score has disappeared completely.
+Este formulario tiene algunos errores. Haz clic en el botón que aumenta la puntuación unas cuantas veces. Observa que no aumenta. A continuación, edita el nombre, y observa que la puntuación se ha "puesto al día" con sus cambios. Por último, edita el apellido y observa que la puntuación ha desaparecido por completo.
-Your task is to fix all of these bugs. As you fix them, explain why each of them happens.
+Tu tarea es arreglar todos estos errores. A medida que los vayas arreglando, explica por qué ocurre cada uno de ellos.
@@ -885,7 +885,7 @@ input { margin-left: 5px; margin-bottom: 5px; }
-Here is a version with both bugs fixed:
+Aquí hay una versión con ambos errores corregidos:
@@ -955,23 +955,23 @@ input { margin-left: 5px; margin-bottom: 5px; }
-The problem with `handlePlusClick` was that it mutated the `player` object. As a result, React did not know that there's a reason to re-render, and did not update the score on the screen. This is why, when you edited the first name, the state got updated, triggering a re-render which _also_ updated the score on the screen.
+El problema con `handlePlusClick` era que mutaba el objeto `player`. Como resultado, React no sabía que había una razón para volver a renderizar, y no actualizaba la puntuación en la pantalla. Por eso, cuando editabas el primer nombre, el estado se actualizaba, provocando un re-renderizado que _también_ actualizaba la puntuación en la pantalla.
-The problem with `handleLastNameChange` was that it did not copy the existing `...player` fields into the new object. This is why the score got lost after you edited the last name.
+El problema con `handleLastNameChange` era que no copiaba los campos existentes de `...player` en el nuevo objeto. Por eso la puntuación se perdía después de editar el último nombre.
-#### Find and fix the mutation {/*find-and-fix-the-mutation*/}
+#### Encontrar y arreglar la mutación {/*find-and-fix-the-mutation*/}
-There is a draggable box on a static background. You can change the box's color using the select input.
+Hay una caja que se puede arrastrar sobre un fondo estático. Puedes cambiar el color de la caja usando la entrada de selección.
-But there is a bug. If you move the box first, and then change its color, the background (which isn't supposed to move!) will "jump" to the box position. But this should not happen: the `Background`'s `position` prop is set to `initialPosition`, which is `{ x: 0, y: 0 }`. Why is the background moving after the color change?
+Pero hay un error. Si mueves la caja primero, y luego cambias su color, el fondo (¡que se supone que no se mueve!) "saltará" a la posición de la caja. Pero esto no debería ocurrir: la prop `position` del `Background` se establece en `initialPosition`, que es `{ x: 0, y: 0 }`. ¿Por qué se mueve el fondo después del cambio de color?
-Find the bug and fix it.
+Encuentra el error y arréglalo.
-If something unexpected changes, there is a mutation. Find the mutation in `App.js` and fix it.
+Si algo inesperado cambia, hay una mutación. Encuentra la mutación en `App.js` y arréglala.
@@ -1121,9 +1121,9 @@ select { margin-bottom: 10px; }
-The problem was in the mutation inside `handleMove`. It mutated `shape.position`, but that's the same object that `initialPosition` points at. This is why both the shape and the background move. (It's a mutation, so the change doesn't reflect on the screen until an unrelated update--the color change--triggers a re-render.)
+El problema estaba en la mutación dentro de `handleMove`. Mutaba `shape.position`, pero ese es el mismo objeto al que apunta `initialPosition`. Por eso tanto la forma como el fondo se mueven. (Es una mutación, por lo que el cambio no se refleja en la pantalla hasta que una actualización no relacionada -el cambio de color- desencadena una nueva renderización).
-The fix is to remove the mutation from `handleMove`, and use the spread syntax to copy the shape. Note that `+=` is a mutation, so you need to rewrite it to use a regular `+` operation.
+La solución es eliminar la mutación de `handleMove`, y utilizar la sintaxis extendida para copiar la forma. Ten en cuenta que `+=` es una mutación, así que tienes que reescribirlo para usar una operación regular `+`.
@@ -1276,9 +1276,9 @@ select { margin-bottom: 10px; }
-#### Update an object with Immer {/*update-an-object-with-immer*/}
+#### Actualizar un objeto con Immer {/*update-an-object-with-immer*/}
-This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `shape` state variable to use it.
+Este es el mismo ejemplo con errores que en el desafío anterior. Esta vez, arregla la mutación usando Immer. Para tu comodidad, `useImmer` ya está importado, así que tienes que cambiar la variable de estado `shape` para utilizarlo.
@@ -1445,7 +1445,7 @@ select { margin-bottom: 10px; }
-This is the solution rewritten with Immer. Notice how the event handlers are written in a mutating fashion, but the bug does not occur. This is because under the hood, Immer never mutates the existing objects.
+Esta es la solución reescrita con Immer. Observa cómo los manejadores de eventos están escritos de forma mutante, pero el error no se produce. Esto se debe a que bajo el capó, Immer nunca muta los objetos existentes.