From 4376d04cf87616637eabe0502f80ed8d76f26e40 Mon Sep 17 00:00:00 2001 From: Valtory Date: Fri, 18 Nov 2022 23:01:24 -0300 Subject: [PATCH] translation complete --- beta/src/content/apis/react/useState.md | 709 ++++++++++++------------ 1 file changed, 355 insertions(+), 354 deletions(-) diff --git a/beta/src/content/apis/react/useState.md b/beta/src/content/apis/react/useState.md index 7a7df1d2f..f3cbb7ca5 100644 --- a/beta/src/content/apis/react/useState.md +++ b/beta/src/content/apis/react/useState.md @@ -1,13 +1,13 @@ --- -title: useState +titulo: useState --- -`useState` is a React Hook that lets you add a [state variable](/learn/state-a-components-memory) to your component. +`useState` es un React Hook que le permite agregar una [variable de estado](/learn/state-a-components-memory) a su componente. ```js -const [state, setState] = useState(initialState) +const [estado, setEstado] = useState(estadoInicial) ``` @@ -16,74 +16,74 @@ const [state, setState] = useState(initialState) --- -## Usage {/*usage*/} +## Uso {/*uso*/} -### Adding state to a component {/*adding-state-to-a-component*/} +### Agregar estado a un componente {/*agregar-estado-a-un-componente*/} -Call `useState` at the top level of your component to declare one or more [state variables.](/learn/state-a-components-memory) +Llamar `useState` en el nivel superior de su componente para declarar una o más [variables de estado.](/learn/state-a-components-memory) -```js [[1, 4, "age"], [2, 4, "setAge"], [3, 4, "42"], [1, 5, "name"], [2, 5, "setName"], [3, 5, "'Taylor'"]] +```js [[1, 4, "edad"], [2, 4, "setEdad"], [3, 4, "42"], [1, 5, "nombre"], [2, 5, "setNombre"], [3, 5, "'Taylor'"]] import { useState } from 'react'; function MyComponent() { - const [age, setAge] = useState(42); - const [name, setName] = useState('Taylor'); + const [edad, setEdad] = useState(42); + const [nombre, setNombre] = useState('Taylor'); // ... ``` - The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment) +La convención es nombrar variables de estado como `[algo, setAlgo]` utilizando la [desestructuración de matrices.](https://javascript.info/destructuring-assignment) -`useState` returns an array with exactly two items: +`useState` devuelve un array con exactamente dos elementos: -1. The current state of this state variable, initially set to the initial state you provided. -2. The `set` function that lets you change it to any other value in response to interaction. +1. El estado actual de esta variable de estado, establecida inicialmente en el estado inicial que proporcionó. +2. La función `set` que le permite cambiarlo a cualquier otro valor en respuesta a la interacción. -To update what’s on the screen, call the `set` function with some next state: +Para actualizar lo que está en la pantalla, llame a la función set con algún estado: -```js [[2, 2, "setName"]] +```js [[2, 2, "setNombre"]] function handleClick() { - setName('Robin'); + setNombre('Robin'); } ``` -React will store the next state, render your component again with the new values, and update the UI. +React almacenará el siguiente estado, renderizará su componente nuevamente con los nuevos valores y actualizará la interfaz de usuario. -Calling the `set` function [**does not** change the current state in the already executing code](#ive-updated-the-state-but-logging-gives-me-the-old-value): + +Llamando a la función `set` [**no cambia** el estado actual en el código que ya se está ejecutando ](#ive-updated-the-state-but-logging-gives-me-the-old-value): ```js {3} function handleClick() { - setName('Robin'); - console.log(name); // Still "Taylor"! + setNombre('Robin'); + console.log(nombre); // Sigue siendo "Taylor"! } ``` - -It only affects what `useState` will return starting from the *next* render. +Solo afecta lo que `useState` devolverá a partir del *siguiente* render. - + -#### Counter (number) {/*counter-number*/} +#### Contador (número) {/*counter-number*/} -In this example, the `count` state variable holds a number. Clicking the button increments it. +En este ejemplo, la variable `contador` contiene un número. Al hacer click en el botón lo incrementa ```js import { useState } from 'react'; -export default function Counter() { - const [count, setCount] = useState(0); +export default function Contador() { + const [contador, setContador] = useState(0); function handleClick() { - setCount(count + 1); + setContador(contador + 1); } return ( ); } @@ -93,9 +93,9 @@ export default function Counter() { -#### Text field (string) {/*text-field-string*/} - -In this example, the `text` state variable holds a string. When you type, `handleChange` reads the latest input value from the browser input DOM element, and calls `setText` to update the state. This allows you to display the current `text` below. +#### Campo de texto (cadena) {/*text-field-string*/} + +En este ejemplo, la variable de estado `texto` contiene una cadena. Cuando escribes,`handleChange` lee el ultimo valor ingresado al elemento input del DOM desde el navegador y llama `setTexto` para actualizar el estado. Esto le permite mostrar el actual `texto` abajo. @@ -103,18 +103,18 @@ In this example, the `text` state variable holds a string. When you type, `handl import { useState } from 'react'; export default function MyInput() { - const [text, setText] = useState('hello'); + const [texto, setTexto] = useState('hola'); function handleChange(e) { - setText(e.target.value); + setTexto(e.target.value); } return ( <> - -

You typed: {text}

- ); @@ -125,9 +125,9 @@ export default function MyInput() { -#### Checkbox (boolean) {/*checkbox-boolean*/} +#### Checkbox (booleano) {/*checkbox-boolean*/} -In this example, the `liked` state variable holds a boolean. When you click the input, `setLiked` updates the `liked` state variable with whether the browser checkbox input is checked. The `liked` variable is used to render the text below the checkbox. +En este ejemplo, la variable de estado `meGusta` contiene un valor booleano. Al hacer click en el checkbox, `setMeGusta` actualiza la variable de estado `meGusta` si es que la entrada del checkbox del navegador fue marcada. La variable `meGusta` se utiliza para representar el texto debajo del checkbox. @@ -135,10 +135,10 @@ In this example, the `liked` state variable holds a boolean. When you click the import { useState } from 'react'; export default function MyCheckbox() { - const [liked, setLiked] = useState(true); + const [meGusta, setMeGusta] = useState(true); function handleChange(e) { - setLiked(e.target.checked); + setMeGusta(e.target.checked); } return ( @@ -146,12 +146,12 @@ export default function MyCheckbox() { -

You {liked ? 'liked' : 'did not like'} this.

+

A ti {meGusta ? 'te gusta' : 'no te gusta'} esto.

); } @@ -161,29 +161,29 @@ export default function MyCheckbox() { -#### Form (two variables) {/*form-two-variables*/} +#### Formulario (dos variables) {/*form-two-variables*/} -You can declare more than one state variable in the same component. Each state variable is completely independent. +Se puede declarar más de una variable de estado en el mismo componente. Cada variable de estado es completamente independiente. ```js import { useState } from 'react'; -export default function Form() { - const [name, setName] = useState('Taylor'); - const [age, setAge] = useState(42); +export default function Formulario() { + const [nombre, setNombre] = useState('Taylor'); + const [edad, setEdad] = useState(42); return ( <> setName(e.target.value)} + value={nombre} + onChange={e => setNombre(e.target.value)} /> - -

Hello, {name}. You are {age}.

+

Hola, {nombre}. Tu tiene {edad} años.

); } @@ -201,84 +201,83 @@ button { display: block; margin-top: 10px; } --- -### Updating state based on the previous state {/*updating-state-based-on-the-previous-state*/} +### Estado de actualización basado en el estado anterior {/*updating-state-based-on-the-previous-state*/} -Suppose the `age` is `42`. This handler calls `setAge(age + 1)` three times: +Supongamos que `edad` es `42`. La función `handler` llama `setEdad(edad + 1)` tres veces: ```js function handleClick() { - setAge(age + 1); // setAge(42 + 1) - setAge(age + 1); // setAge(42 + 1) - setAge(age + 1); // setAge(42 + 1) + setEdad(edad + 1); // setEdad(42 + 1) + setEdad(edad + 1); // setEdad(42 + 1) + setEdad(edad + 1); // setEdad(42 + 1) } ``` +Sin embargo, después de un click, `edad` solo será `43` en lugar de 45! Esto se debe a que llamar a la función `set ` no actualizará la variable de estado `edad` en el código que ya se está ejecutando. Así que cada llamada `setAge(age + 1)` se convierte en `setEdad(43)`. -However, after one click, `age` will only be `43` rather than `45`! This is because calling the `set` function [does not update](/learn/state-as-a-snapshot) the `age` state variable in the already running code. So each `setAge(age + 1)` call becomes `setAge(43)`. +Para resolver este problema, **puede pasar una función de actualización** a `setEdad` en lugar del siguiente estado: -To solve this problem, **you may pass an *updater function*** to `setAge` instead of the next state: - -```js [[1, 2, "a", 0], [2, 2, "a + 1"], [1, 3, "a", 0], [2, 3, "a + 1"], [1, 4, "a", 0], [2, 4, "a + 1"]] +```js [[1, 2, "e ", 2], [2, 2, "e + 1"], [1, 3, "e ", 2], [2, 3, "e + 1"], [1, 4, "e ", 2], [2, 4, "e + 1"]] function handleClick() { - setAge(a => a + 1); // setAge(42 => 43) - setAge(a => a + 1); // setAge(43 => 44) - setAge(a => a + 1); // setAge(44 => 45) + setEdad(e => e + 1); // setEdad(42 => 43) + setEdad(e => e + 1); // setEdad(43 => 44) + setEdad(e => e + 1); // setEdad(44 => 45) } ``` -Here, `a => a + 1` is your updater function. It takes the pending state and calculates the next state from it. +Aqui, `e => e + 1` es la función de actualización. Toma el estado pendiente y calcula el siguiente estado a partir de él. -React puts your updater functions in a [queue.](/learn/queueing-a-series-of-state-updates) Then, during the next render, it will call them in the same order: +React pone sus funciones de actualización en una [cola.](/learn/queueing-a-series-of-state-updates) Entonces, durante el siguiente renderizado, las llamara en el mismo orden: -1. `a => a + 1` will receive `42` as the pending state and return `43` as the next state. -1. `a => a + 1` will receive `43` as the pending state and return `44` as the next state. -1. `a => a + 1` will receive `44` as the pending state and return `45` as the next state. +1. `e => e + 1` recibirá `42` como estado pendiente y devolverá `43` como el siguiente estado. +1. `e => e + 1` recibirá `43` como estado pendiente y devolverá `44` como el siguiente estado. +1. `e => e + 1` recibirá `44` como estado pendiente y devolverá `45` como el siguiente estado. -There are no other queued updates, so React will store `45` as the current state in the end. +No hay otras actualizaciones en cola, por lo que React almacenará `45` como el estado actual al final. -By convention, it's common to name the pending state argument for the first letter of the state variable name, like `a` for `age`. However, you may also call it like `prevAge` or something else that you find clearer. +Por convención, es común nombrar el argumento de estado pendiente como la primera letra del nombre de la variable de estado, como `e` para `edad`. No obstante, también puedes llamarlo como `prevEdad` o cualquier otra cosa que te resulte más clara. -React may [call your updaters twice](#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](/learn/keeping-components-pure) +React puede [llamar a sus actualizadores dos veces](#my-initializer-or-updater-function-runs-twice) en desarrollo para verificar que sean [puros.](/learn/keeping-components-pure) - + -You might hear a recommendation to always write code like `setAge(a => a + 1)` if the state you're setting is calculated from the previous state. There is no harm in it, but it is also not always necessary. +Es posible que escuches una recomendación para escribir siempre código como `setEdad(e => e + 1)` si el estado que está configurando se calcula a partir del estado anterior. No hay daño en ello, pero tampoco siempre es necesario. -In most cases, there is no difference between these two approaches. React always makes sure that for intentional user actions, like clicks, the `age` state variable would be updated before the next click. This means there is no risk of a click handler seeing a "stale" `age` at the beginning of the event handler. +En la mayoría de los casos, no hay diferencia entre estos dos enfoques. React siempre se asegura de que para las acciones intencionales del usuario, como los click, la variable de estado `edad` se actualizará antes del siguiente click. Esto significa que no hay riesgo de que un controlador de clicks vea un mensaje "obsoleto" de `edad` al comienzo del controlador de eventos. -However, if you do multiple updates within the same event, updaters can be helpful. They're also helpful if accessing the state variable itself is inconvenient (you might run into this when optimizing re-renders). +Sin embargo, si realiza varias actualizaciones dentro del mismo evento, los actualizadores pueden ser útiles. También son útiles si acceder a la variable de estado en sí es un inconveniente (es posible que te encuentres con esto al optimizar los renderizados). -If you prefer consistency over slightly more verbose syntax, it's reasonable to always write an updater if the state you're setting is calculated from the previous state. If it's calculated from the previous state of some *other* state variable, you might want to combine them into one object and [use a reducer.](/learn/extracting-state-logic-into-a-reducer) +Si prefiere la coherencia a una sintaxis un poco más detallada, es razonable escribir siempre un actualizador si el estado que está configurando se calcula a partir del estado anterior. Si se calcula a partir del estado anterior de alguna otra variable de estado, es posible que desee combinarlos en un solo objeto y [uses un reducer.](/learn/extracting-state-logic-into-a-reducer) - + -#### Passing the updater function {/*passing-the-updater-function*/} +#### Pasar la funcion de actualización {/*passing-the-updater-function*/} -This example passes the updater function, so the "+3" button works. +Este ejemplo pasa la función de actualización, por lo que funciona el botón "+3". ```js import { useState } from 'react'; -export default function Counter() { - const [age, setAge] = useState(42); +export default function Contador() { + const [edad, setEdad] = useState(42); - function increment() { - setAge(a => a + 1); + function incremento() { + setEdad(a => a + 1); } return ( <> -

Your age: {age}

+

Tu edad: {edad}

); @@ -294,25 +293,25 @@ h1 { display: block; margin: 10px; } -#### Passing the next state directly {/*passing-the-next-state-directly*/} +#### Pasando el siguiente estado directamente {/*passing-the-next-state-directly*/} -This example **does not** pass the updater function, so the "+3" button **doesn't work as intended**. +Este ejemplo **no pasa** la función de actualización, por lo que el botón "+3" **no funciona según lo previsto** . ```js import { useState } from 'react'; -export default function Counter() { - const [age, setAge] = useState(42); +export default function Contador() { + const [edad, setEdad] = useState(42); function increment() { - setAge(age + 1); + setEdad(edad + 1); } return ( <> -

Your age: {age}

+

Tu edad: {edad}

+ settitulo(''); + onAddTodo(titulo); + }}>Agregar ) } @@ -661,24 +663,24 @@ function Task({ todo, onChange, onDelete }) { todoContent = ( <> { onChange({ ...todo, - title: e.target.value + titulo: e.target.value }); }} /> ); } else { todoContent = ( <> - {todo.title} + {todo.titulo} ); @@ -697,7 +699,7 @@ function Task({ todo, onChange, onDelete }) { /> {todoContent} ); @@ -714,9 +716,9 @@ ul, li { margin: 0; padding: 0; } -#### Writing concise update logic with Immer {/*writing-concise-update-logic-with-immer*/} +#### Escribir lógica de actualización concisa con Immer {/*writing-concise-update-logic-with-immer*/} -If updating arrays and objects without mutation feels tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code. Immer lets you write concise code as if you were mutating objects, but under the hood it performs immutable updates: +Si actualizar matrices y objetos sin mutación resulta tedioso, puede usar una biblioteca como [Immer](https://github.com/immerjs/use-immer) para reducir el código repetitivo. Immer te permite escribir código conciso como si estuvieras mutando objetos, pero bajo el capó realiza actualizaciones inmutables: @@ -726,9 +728,9 @@ import { useImmer } from 'use-immer'; let nextId = 3; const initialList = [ - { id: 0, title: 'Big Bellies', seen: false }, - { id: 1, title: 'Lunar Landscape', seen: false }, - { id: 2, title: 'Terracotta Army', seen: true }, + { id: 0, titulo: 'Big Bellies', seen: false }, + { id: 1, titulo: 'Paisaje Lunar', seen: false }, + { id: 2, titulo: 'Ejército de Terracota', seen: true }, ]; export default function BucketList() { @@ -745,8 +747,8 @@ export default function BucketList() { return ( <> -

Art Bucket List

-

My list of art to see:

+

Lista de cubo de arte

+

Mi lista de arte para ver:

@@ -770,7 +772,7 @@ function ItemList({ artworks, onToggle }) { ); }} /> - {artwork.title} + {artwork.titulo} ))} @@ -805,73 +807,73 @@ function ItemList({ artworks, onToggle }) { --- -### Avoiding recreating the initial state {/*avoiding-recreating-the-initial-state*/} +### Evitar recrear el estado inicial {/*avoiding-recreating-the-initial-state*/} -React saves the initial state once and ignores it on the next renders. +React guarda el estado inicial una vez y lo ignora en los próximos renderizados. ```js function TodoList() { - const [todos, setTodos] = useState(createInitialTodos()); + const [todos, setTodos] = useState(crearIniciarTodos()); // ... ``` -Although the result of `createInitialTodos()` is only used for the initial render, you're still calling this function on every render. This can be wasteful if it's creating large arrays or performing expensive calculations. +Aunque el resultado de `crearIniciarTodos()` solo se usa para el renderizado inicial, todavía está llamando a esta función en cada renderizado. Esto puede ser un desperdicio si se trata de crear matrices grandes o realizar cálculos costosos. -To solve this, you may **pass it as an _initializer_ function** to `useState` instead: +Para resolver esto, puede **pasarlo como una función _initializer_** a `useState` en su lugar: ```js function TodoList() { - const [todos, setTodos] = useState(createInitialTodos); + const [todos, setTodos] = useState(crearInicialTodos); // ... ``` -Notice that you’re passing `createInitialTodos`, which is the *function itself*, and not `createInitialTodos()`, which is the result of calling it. If you pass a function to `useState`, React will only call it during initialization. +Observa que está pasando `crearIniciarTodos`, que es la *función misma*, y no `crearIniciarTodos()`, que es el resultado de llamarla. Si pasa una función a `useState`, React solo la llamará durante la inicialización. -React may [call your initializers twice](#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](/learn/keeping-components-pure) +React puede [llamar a sus inicializadores dos veces](#my-initializer-or-updater-function-runs-twice) en desarrollo para verificar que sean [puros.](/learn/manteniendo-componentes-puros) - + -#### Passing the initializer function {/*passing-the-initializer-function*/} +#### Pasando la función de inicializador {/*passing-the-initializer-function*/} -This example passes the initializer function, so the `createInitialTodos` function only runs during initialization. It does not run when component re-renders, such as when you type into the input. +Este ejemplo pasa la función de inicialización, por lo que la función `crearIniciarTodos` solo se ejecuta durante la inicialización. No se ejecuta cuando el componente se vuelve a renderizar, como cuando escribe en la entrada. ```js import { useState } from 'react'; -function createInitialTodos() { +function crearIniciarTodos() { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, - text: 'Item ' + (i + 1) + texto: 'Item ' + (i + 1) }); } return initialTodos; } export default function TodoList() { - const [todos, setTodos] = useState(createInitialTodos); - const [text, setText] = useState(''); + const [todos, setTodos] = useState(crearIniciarTodos); + const [texto, setTexto] = useState(''); return ( <> setText(e.target.value)} /> + }}>Agregar
    {todos.map(item => (
  • - {item.text} + {item.texto}
  • ))}
@@ -884,47 +886,47 @@ export default function TodoList() { -#### Passing the initial state directly {/*passing-the-initial-state-directly*/} +#### Pasando el estado inicial directamente {/*passing-the-initial-state-directly*/} -This example **does not** pass the initializer function, so the `createInitialTodos` function runs on every render, such as when you type into the input. There is no observable difference in behavior, but this code is less efficient. +Este ejemplo **no** pasa la función de inicialización, por lo que la función `crearIniciarTodos` se ejecuta en cada representación, como cuando escribes en la entrada. No hay una diferencia observable en el comportamiento, pero este código es menos eficiente. ```js import { useState } from 'react'; -function createInitialTodos() { +function crearIniciarTodos() { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, - text: 'Item ' + (i + 1) + texto: 'Item ' + (i + 1) }); } return initialTodos; } export default function TodoList() { - const [todos, setTodos] = useState(createInitialTodos()); - const [text, setText] = useState(''); + const [todos, setTodos] = useState(crearIniciarTodos()); + const [texto, setTexto] = useState(''); return ( <> setText(e.target.value)} + value={texto} + onChange={e => setTexto(e.target.value)} />
    {todos.map(item => (
  • - {item.text} + {item.texto}
  • ))}
@@ -941,13 +943,13 @@ export default function TodoList() { --- -### Resetting state with a key {/*resetting-state-with-a-key*/} +### Restablecimiento de estado con una key {/*resetting-state-with-a-key*/} -Typically, you might encounter the `key` attribute when [rendering lists.](/learn/rendering-lists) However, it also serves another purpose. +Por lo general, es posible que encuentre el atributo `key` al [representar listas.](/learn/rendering-lists) Sin embargo, también tiene otro propósito. -You can **reset a component's state by passing a different `key` to a component.** In this example, the Reset button changes the `version` state variable, which we pass as a `key` to the `Form`. When the `key` changes, React re-creates the `Form` component (and all of its children) from scratch, so its state gets reset. +Puede **restablecer el estado de un componente pasando una `key` diferente a un componente.** En este ejemplo, el botón Restablecer cambia la variable de estado `versión`, que pasamos como una `key` al `Formulario`. Cuando la `key` cambia, React vuelve a crear el componente `Formulario` (y todos sus elementos secundarios) desde cero, por lo que su estado se restablece. -Read [preserving and resetting state](/learn/preserving-and-resetting-state) to learn more. +Lea [preservar y restablecer el estado](/aprender/preservar-y-restablecer-el-estado) para obtener más información. @@ -964,21 +966,21 @@ export default function App() { return ( <> -
+ ); } -function Form() { - const [name, setName] = useState('Taylor'); +function Formulario() { + const [nombre, setNombre] = useState('Taylor'); return ( <> setName(e.target.value)} + value={nombre} + onChange={e => setNombre(e.target.value)} /> -

Hello, {name}.

+

Hola, {nombre}.

); } @@ -992,64 +994,63 @@ button { display: block; margin-bottom: 20px; } --- -### Storing information from previous renders {/*storing-information-from-previous-renders*/} +### Almacenamiento de información de renders anteriores {/*storing-information-from-previous-renders*/} -Usually, you will update state in event handlers. However, in rare cases you might want to adjust state in response to rendering -- for example, you might want to change a state variable when a prop changes. +Por lo general, actualizará el estado en los controladores de eventos. Sin embargo, en casos excepcionales, es posible que desee ajustar el estado en respuesta a la representación; por ejemplo, es posible que desee cambiar una variable de estado cuando cambia una propiedad. -In most cases, you don't need this: +En la mayoría de los casos, no necesita esto: -* **If the value you need can be computed entirely from the current props or other state, [remove that redundant state altogether.](/learn/choosing-the-state-structure#avoid-redundant-state)** If you're worried about recomputing too often, the [`useMemo` Hook](/apis/react/usememo) can help. -* If you want to reset the entire component tree's state, [pass a different `key` to your component.](#resetting-state-with-a-key) -* If you can, update all the relevant state in the event handlers. +* **Si el valor que necesita se puede calcular completamente a partir de los accesorios actuales u otro estado, [elimine ese estado redundante por completo.](/learn/choosing-the-state-structure#avoid-redundant-state)** Si te preocupa volver a calcular con demasiada frecuencia, el [Hook `useMemo`](/apis/react/usememo) puede ayudarte. +* Si desea restablecer el estado de todo el árbol de componentes, [pase una `key` diferente a su componente.](#resetting-state-with-a-key) +* Si puede, actualice todo el estado relevante en los controladores de eventos. -In the rare case that none of these apply, there is a pattern you can use to update state based on the values that have been rendered so far, by calling a `set` function while your component is rendering. +En el raro caso de que ninguno de estos se aplique, hay un patrón que puede usar para actualizar el estado en función de los valores que se han representado hasta el momento, llamando a una función `set` mientras su componente se está procesando. -Here's an example. This `CountLabel` component displays the `count` prop passed to it: +Aquí hay un ejemplo. Este componente `EtiquetaDeConteo` muestra la propiedad `conteo` que se le pasó: -```js CountLabel.js -export default function CountLabel({ count }) { - return

{count}

+```js EtiquetaDeConteo.js +export default function EtiquetaDeConteo({ conteo }) { + return

{conteo}

} ``` - -Say you want to show whether the counter has *increased or decreased* since the last change. The `count` prop doesn't tell you this -- you need to keep track of its previous value. Add the `prevCount` state variable to track it. Add another state variable called `trend` to hold whether the count has increased or decreased. Compare `prevCount` with `count`, and if they're not equal, update both `prevCount` and `trend`. Now you can show both the current count prop and *how it has changed since the last render*. +Digamos que quiere mostrar si el contador ha *aumentado o disminuido* desde el último cambio. El accesorio `conteo` no le dice esto, -- necesita realizar un seguimiento de su valor anterior. Agregue la variable de estado `prevConteo` para realizar un seguimiento. Agregue otra variable de estado llamada `trend` para determinar si el conteo ha aumentado o disminuido. Compare `prevConteo` con `conteo` y, si no son iguales, actualice tanto `prevConteo` como `trend`. Ahora puede mostrar tanto el accesorio de conteo actual como *cómo ha cambiado desde el último renderizado*. ```js App.js import { useState } from 'react'; -import CountLabel from './CountLabel.js'; +import EtiquetaDeConteo from './EtiquetaDeConteo.js'; export default function App() { - const [count, setCount] = useState(0); + const [conteo, setConteo] = useState(0); return ( <> - - - + ); } ``` -```js CountLabel.js active +```js EtiquetaDeConteo.js active import { useState } from 'react'; -export default function CountLabel({ count }) { - const [prevCount, setPrevCount] = useState(count); +export default function EtiquetaDeConteo({ conteo }) { + const [prevConteo, setprevConteo] = useState(conteo); const [trend, setTrend] = useState(null); - if (prevCount !== count) { - setPrevCount(count); - setTrend(count > prevCount ? 'increasing' : 'decreasing'); + if (prevConteo !== conteo) { + setprevConteo(conteo); + setTrend(conteo > prevConteo ? 'incrementando' : 'disminuyendo'); } return ( <> -

{count}

- {trend &&

The count is {trend}

} +

{conteo}

+ {trend &&

El conteo está {trend}

} ); } @@ -1061,9 +1062,10 @@ button { margin-bottom: 10px; }
-Note that if you call a `set` function while rendering, it must be inside a condition like `prevCount !== count`, and there must be a call like `setPrevCount(count)` inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the *currently rendering* component like this. Calling the `set` function of *another* component during rendering is an error. Finally, your `set` call should still [update state without mutation](#updating-objects-and-arrays-in-state) -- this special case doesn't mean you can break other rules of [pure functions.](/learn/keeping-components-pure) +Tenga en cuenta que si llama a una función `set` durante la renderización, debe estar dentro de una condición como `prevConteo !== conteo`, y debe haber una llamada como `setPrevConteo(conteo)` dentro de la condición. De lo contrario, su componente se volvería a procesar en un bucle hasta que se bloquee. Además, solo puede actualizar el estado del componente *actualmente renderizado* de esta manera. Llamar a la función `set` de *otro* componente durante el renderizado es un error. Finalmente, su llamada `set` aún debería [actualizar el estado sin mutación](#updating-objects-and-arrays-in-state) -- este caso especial no significa que pueda romper otras reglas de [funciones puras.](/learn/keeping-components-pure) + +Este patrón puede ser difícil de entender y, por lo general, es mejor evitarlo. Sin embargo, es mejor que actualizar el estado en un efecto. Cuando llamas a la función `set` durante el renderizado, React volverá a renderizar ese componente inmediatamente después de que tu componente salga con una declaración `return` y antes de renderizar a los elementos secundarios. De esta manera, sus hijos no necesitan renderizar dos veces. El resto de la función de su componente aún se ejecutará (y el resultado se descartará), pero si su condición está por debajo de todas las llamadas a Hooks, puede agregar un `retorno` anticipado dentro de él para reiniciar el renderizado antes. -This pattern can be hard to understand and is usually best avoided. However, it's better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don't need to render twice. The rest of your component function will still execute (and the result will be thrown away), but if your condition is below all the calls to Hooks, you may add an early `return;` inside it to restart rendering earlier. --- @@ -1071,123 +1073,122 @@ This pattern can be hard to understand and is usually best avoided. However, it' ### `useState(initialState)` {/*usestate*/} -Call `useState` at the top level of your component to declare a [state variable.](/learn/state-a-components-memory) +Llame a `useState` en el nivel superior de su componente para declarar una [variable de estado](/learn/state-a-components-memory). ```js import { useState } from 'react'; function MyComponent() { - const [age, setAge] = useState(28); - const [name, setName] = useState('Taylor'); + const [edad, setEdad] = useState(28); + const [nombre, setNombre] = useState('Taylor'); const [todos, setTodos] = useState(() => createTodos()); // ... ``` -The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment) +La convención es nombrar variables de estado como `[algo, setAlgo]` usando [desestructuración de matriz](https://javascript.info/destructuring-assignment). -[See more examples above.](#examples-basic) +[Vea más ejemplos arriba.](#examples-basic) -#### Parameters {/*parameters*/} +#### Parameteros {/*parameters*/} -* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render. - * If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example above.](#avoiding-recreating-the-initial-state) +* `initialState`: El valor que desea que tenga el estado inicialmente. Puede ser un valor de cualquier tipo, pero hay un comportamiento especial para las funciones. Este argumento se ignora después del renderizado inicial. + * Si pasa una función como `initialState`, se tratará como una _función inicializadora_. Debe ser pura, no debe aceptar argumentos y debe devolver un valor de cualquier tipo. React llamará a su función de inicialización al inicializar el componente y almacenará su valor de retorno como el estado inicial. [Vea un ejemplo arriba.](#avoiding-recreating-the-initial-state) + #### Returns {/*returns*/} -`useState` returns an array with exactly two values: +`useState` devuelve una matriz con exactamente dos valores: -1. The current state. During the first render, it will match the `initialState` you have passed. -2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render. +1. El estado actual. Durante el primer renderizado, coincidirá con el `initialState` que haya pasado. +2. La [función `set`](#setstate) que le permite actualizar el estado a un valor diferente y desencadenar una nueva representación. -#### Caveats {/*caveats*/} - -* `useState` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it. -* In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored. +#### Advertencias {/*caveats*/} +* `useState` es un Hook, por lo que solo puede llamarlo **en el nivel superior de su componente** o sus propios Hooks. No puedes llamarlo dentro de bucles o condiciones. Si lo necesita, extraiga un nuevo componente y mueva el estado a él. +* En [Modo estricto](/apis/react/StrictMode), React **llamará a su función de inicialización dos veces** para [ayudarlo a encontrar impurezas accidentales.](#my-initializer-or-updater-function-runs-twoveces) Este es un comportamiento exclusivo de desarrollo y no afecta la producción. Si su función de inicialización es pura (como debería ser), esto no debería afectar la lógica de su componente. Se ignorará el resultado de una de las llamadas. --- -### `set` functions, like `setSomething(nextState)` {/*setstate*/} +### Funciones `set` , como `setAlgo(siguienteEstado)` {/*setstate*/} -The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state: +La función `set` devuelta por `useState` le permite actualizar el estado a un valor diferente y desencadenar una nueva representación. Puede pasar el siguiente estado directamente, o una función que lo calcule a partir del estado anterior: ```js -const [name, setName] = useState('Edward'); +const [nombre, setNombre] = useState('Edward'); function handleClick() { - setName('Taylor'); - setAge(a => a + 1); + setNombre('Taylor'); + setEdad(a => a + 1); // ... ``` -#### Parameters {/*setstate-parameters*/} +#### Parametros {/*setstate-parameters*/} -* `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions. - * If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example above.](#updating-state-based-on-the-previous-state) + * `siguienteEstado`: El valor que desea que tenga el estado. Puede ser un valor de cualquier tipo, pero hay un comportamiento especial para las funciones. + * Si pasa una función como `siguienteEstado`, se tratará como una _función de actualización_. Debe ser puro, debe tomar el estado pendiente como único argumento y debe devolver el siguiente estado. React pondrá su función de actualización en una cola y volverá a renderizar su componente. Durante el próximo renderizado, React calculará el siguiente estado aplicando todas las actualizaciones en cola al estado anterior. [Vea un ejemplo arriba.](#updating-state-based-on-the-previous-state) #### Returns {/*setstate-returns*/} -`set` functions do not have a return value. - -#### Caveats {/*setstate-caveats*/} +Las funciones `set` no tienen un valor de retorno. -* The `set` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `set` function, [you will still get the old value](#ive-updated-the-state-but-logging-gives-me-the-old-value) that was on the screen before your call. +#### Advertencias {/*setstate-caveats*/} -* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn't affect your code. +* La función `set` **solo actualiza la variable de estado para el *próximo* renderizado**. Si lee la variable de estado después de llamar a la función `set`, [todavía obtendrá el valor anterior](#ive-updated-the-state-but-logging-gives-me-the-old-value) que estaba en la pantalla antes de su llamada. -* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/apis/react-dom/flushSync) +* Si el nuevo valor que proporciona es idéntico al `estado` actual, según lo determinado por un [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is), React **omitirá volver a renderizar el componente y sus elementos secundarios.** Esta es una optimización. Aunque en algunos casos React aún puede necesitar llamar a su componente antes de omitir a los elementos secundarios, no debería afectar su código. -* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example above.](#storing-information-from-previous-renders) +* Reaccionar [actualizaciones de estado por lotes.](/learn/queueing-a-series-of-state-updates) Actualiza la pantalla **después de que todos los controladores de eventos se hayan ejecutado** y hayan llamado a sus funciones `set`. Esto evita múltiples renderizaciones durante un solo evento. En el raro caso de que necesite forzar a React a actualizar la pantalla antes, por ejemplo, para acceder al DOM, puede usar [`flushSync`.](/apis/react-dom/flushsync) -* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored. +* Llamar a la función `set` *durante el renderizado* solo está permitido desde el componente de renderizado actual. React descartará su salida e inmediatamente intentará renderizarla nuevamente con el nuevo estado. Este patrón rara vez se necesita, pero puede usarlo para **almacenar información de los renderizados anteriores**. [Vea un ejemplo arriba.](#storing-information-from-previous-renders) +* En [Modo estricto](/apis/react/StrictMode), React **llamará a su función de actualización dos veces** para [ayudarlo a encontrar impurezas accidentales.](#my-initializer-or-updater-function-runs-twice) Este es un comportamiento exclusivo de desarrollo y no afecta la producción. Si su función de actualización es pura (como debería ser), esto no debería afectar la lógica de su componente. Se ignorará el resultado de una de las llamadas. --- -## Troubleshooting {/*troubleshooting*/} +## Solución de problemas {/*troubleshooting*/} -### I've updated the state, but logging gives me the old value {/*ive-updated-the-state-but-logging-gives-me-the-old-value*/} +### He actualizado el estado, pero el registro me da el valor anterior {/*ive-updated-the-state-but-logging-gives-me-the-old-value*/} -Calling the `set` function **does not change state in the running code**: +Llamar a la función `set` **no cambia el estado en el código en ejecución**: ```js {4,5,8} function handleClick() { - console.log(count); // 0 + console.log(conteo); // 0 - setCount(count + 1); // Request a re-render with 1 - console.log(count); // Still 0! + setConteo(conteo + 1); // Solicitar un re-render con 1 + console.log(conteo); // Todavía 0! setTimeout(() => { - console.log(count); // Also 0! + console.log(conteo); // Tambien es 0! }, 5000); } ``` -This is because [states behaves like a snapshot.](/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `count` JavaScript variable in your already-running event handler. +Esto se debe a que [los estados se comportan como una instantánea.](/learn/state-as-a-snapshot) La actualización del estado solicita otro procesamiento con el nuevo valor del estado, pero no afecta la variable de JavaScript `conteo` en su evento Handler que ya se está ejecutando. -If you need to use the next state, you can save it in a variable before passing it to the `set` function: +Si necesita usar el siguiente estado, puede guardarlo en una variable antes de pasarlo a la función `set`: ```js -const nextCount = count + 1; -setCount(nextCount); +const nextconteo = conteo + 1; +setConteo(nextconteo); -console.log(count); // 0 -console.log(nextCount); // 1 +console.log(conteo); // 0 +console.log(nextconteo); // 1 ``` --- -### I've updated the state, but the screen doesn't update {/*ive-updated-the-state-but-the-screen-doesnt-update*/} +### He actualizado el estado, pero la pantalla no se actualiza {/*ive-updated-the-state-but-the-screen-doesnt-update*/} -React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly: +React **ignorará su actualización si el siguiente estado es igual al estado anterior**, según lo determine un [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Esto generalmente sucede cuando cambia un objeto o una matriz en el estado directamente : ```js -obj.x = 10; // 🚩 Wrong: mutating existing object -setObj(obj); // 🚩 Doesn't do anything +obj.x = 10; // 🚩 Incorrecto: mutar objeto existente +setObj(obj); // 🚩 No hace nada ``` -You mutated an existing `obj` object and passed it back to `setObj`, so React ignored the update. To fix this, you need to ensure that you're always [_replacing_ objects and arrays in state instead of _mutating_ them](#updating-objects-and-arrays-in-state): +Mutó un objeto `obj` existente y lo devolvió a `setObj`, por lo que React ignoró la actualización. Para solucionar esto, debe asegurarse de estar siempre [_reemplazando_ objetos y arreglos en estado en lugar de _mutarlos_](#updating-objects-and-arrays-in-state) : ```js -// ✅ Correct: creating a new object +// ✅ Correcto: creando un nuevo objeto setObj({ ...obj, x: 10 @@ -1196,93 +1197,93 @@ setObj({ --- -### I'm getting an error: "Too many re-renders" {/*im-getting-an-error-too-many-re-renders*/} +### Recibo un error: "Demasiados renderizados" {/*im-getting-an-error-too-many-re-renders*/} -You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you're unconditionally setting state *during render*, so your component enters a loop: render, set state (which causes a render), render, set state (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler: +Es posible que reciba un error que diga: `Demasiados renderizados. React limita la cantidad de renderizaciones para evitar un bucle infinito.` Por lo general, esto significa que está configurando incondicionalmente el estado *durante el renderizado*, por lo que su componente entra en un bucle: renderizar, establecer el estado (lo que provoca un renderizado), renderizar, establecer estado (que provoca un renderizado), y así sucesivamente. Muy a menudo, esto se debe a un error al especificar un controlador de eventos: ```js {1-2} -// 🚩 Wrong: calls the handler during render -return +// 🚩 Incorrecto: llama al controlador durante el procesamiento +return -// ✅ Correct: passes down the event handler -return +// ✅ Correcto: pasa el controlador de eventos +return -// ✅ Correct: passes down an inline function -return +// ✅ Correcto: transmite una función en línea +return ``` -If you can't find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `set` function call responsible for the error. +Si no puede encontrar la causa de este error, haga clic en la flecha al lado del error en la consola y mire a través de la pila de JavaScript para encontrar la llamada de función `set` específica responsable del error. --- -### My initializer or updater function runs twice {/*my-initializer-or-updater-function-runs-twice*/} +### Mi función de inicializador o actualizador se ejecuta dos veces {/*my-initializer-or-updater-function-runs-twice*/} -In [Strict Mode](/apis/react/StrictMode), React will call some of your functions twice instead of once: +En [Modo estricto](/apis/react/StrictMode), React llamará a algunas de sus funciones dos veces en lugar de una: ```js {2,5-6,11-12} function TodoList() { - // This component function will run twice for every render. + // Esta función de componente se ejecutará dos veces por cada procesamiento. const [todos, setTodos] = useState(() => { - // This initializer function will run twice during initialization. - return createTodos(); + // Esta función de inicialización se ejecutará dos veces durante la inicialización. + return crearTodos(); }); function handleClick() { setTodos(prevTodos => { - // This updater function will run twice for every click. - return [...prevTodos, createTodo()]; + // Esta función de actualización se ejecutará dos veces por cada click. + return [...prevTodos, crearTodo()]; }); } // ... ``` -This is expected and shouldn't break your code. +Esto se espera y no debería romper su código. -This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and updater functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes and fix it. +Este comportamiento de **solo desarrollo** lo ayuda a [mantener los componentes puros.](/learn/keeping-components-pure) React usa el resultado de una de las llamadas e ignora el resultado de la otra llamada. Siempre que sus funciones de componente, inicializador y actualizador sean puras, esto no debería afectar su lógica. Sin embargo, si son impuros accidentalmente, esto le ayuda a detectar los errores y corregirlos. -For example, this impure updater function mutates an array in state: +Por ejemplo, esta función de actualización impura muta una matriz en el estado: ```js {2,3} setTodos(prevTodos => { - // 🚩 Mistake: mutating state - prevTodos.push(createTodo()); + // 🚩 Error: estado mutando + prevTodos.push(crearTodo()); }); ``` -Because React calls your updater function twice, you'll see the todo was added twice, so you'll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](#updating-objects-and-arrays-in-state): +Debido a que React llama a su función de actualización dos veces, verá que la tarea pendiente se agregó dos veces, por lo que sabrá que hay un error. En este ejemplo, puede corregir el error [reemplazando la matriz en lugar de mutarla](#updating-objects-and-arrays-in-state): ```js {2,3} setTodos(prevTodos => { - // ✅ Correct: replacing with new state - return [...prevTodos, createTodo()]; + // ✅ Correcto: reemplazando con nuevo estado + return [...prevTodos, crearTodo()]; }); ``` -Now that this updater function is pure, calling it an extra time doesn't make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and updater functions need to be pure.** Event handlers don't need to be pure, so React will never call your event handlers twice. +Ahora que esta función de actualización es pura, llamarla un tiempo extra no hace una diferencia en el comportamiento. Es por eso que React llamarlo dos veces lo ayuda a encontrar errores. **Solo las funciones de componente, inicializador y actualizador deben ser puras.** Los controladores de eventos no necesitan ser puros, por lo que React nunca llamará a sus controladores de eventos dos veces. -Read [keeping components pure](/learn/keeping-components-pure) to learn more. +Lea [manteniendo los componentes puros](/learn/keeping-components-pure) para obtener más información. --- -### I'm trying to set state to a function, but it gets called instead {/*im-trying-to-set-state-to-a-function-but-it-gets-called-instead*/} +### Estoy tratando de establecer el estado de una función, pero es llamado en su lugar {/*im-trying-to-set-state-to-a-function-but-it-gets-called-instead*/} -You can't put a function into state like this: +No puedes poner una función en un estado como este: ```js -const [fn, setFn] = useState(someFunction); +const [fn, setFn] = useState(algunaFuncion); function handleClick() { - setFn(someOtherFunction); + setFn(algunaOtraFuncion); } ``` -Because you're passing a function, React assumes that `someFunction` is an [initializer function](#avoiding-recreating-the-initial-state), and that `someOtherFunction` is an [updater function](#updating-state-based-on-the-previous-state), so it tries to call them and store the result. To actually *store* a function, you have to put `() =>` before them in both cases. Then React will store the functions you pass. +Debido a que estás pasando una función, React asume que `algunaFuncion` es una [función inicializadora](#avoiding-recreating-the-initial-state), y que `algunaOtraFuncion` es una [función actualizadora](#updating-state-based-on-the-previous-state), por lo que intenta llamarlos y almacenar el resultado. Para realmente *almacenar* una función, tienes que poner `() =>` delante de ellos en ambos casos. Entonces React almacenará las funciones que pase. ```js {1,4} -const [fn, setFn] = useState(() => someFunction); +const [fn, setFn] = useState(() => algunaFuncion); function handleClick() { - setFn(() => someOtherFunction); + setFn(() => algunaOtraFuncion); } ```