|
1 | 1 | ---
|
2 | 2 | id: faq-state
|
3 |
| -title: Component State |
| 3 | +title: Estado del componente |
4 | 4 | permalink: docs/faq-state.html
|
5 | 5 | layout: docs
|
6 | 6 | category: FAQ
|
7 | 7 | ---
|
8 | 8 |
|
9 |
| -### What does `setState` do? |
| 9 | +### ¿Qué hace `setState`? |
10 | 10 |
|
11 |
| -`setState()` schedules an update to a component's `state` object. When state changes, the component responds by re-rendering. |
| 11 | +`setState()` programa una actualización al objeto `estado` de un componente. Cuando el estado cambia, el componente responde volviendo a renderizar. |
12 | 12 |
|
13 |
| -### What is the difference between `state` and `props`? |
| 13 | +### ¿Cuál es la diferencia entre `state` y `props`? |
14 | 14 |
|
15 |
| -[`props`](/docs/components-and-props.html) (short for "properties") and [`state`](/docs/state-and-lifecycle.html) are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: `props` get passed *to* the component (similar to function parameters) whereas `state` is managed *within* the component (similar to variables declared within a function). |
| 15 | +[`props`](/docs/components-and-props.html) (abreviatura de "*properties*") y [`state`](/docs/state-and-lifecycle.html) son objetos planos de JavaScript. Mientras ambos contienen información que influye en el resultado del render, son diferentes debido a una importante razón: `props` se pasa *al* componente (similar a los parámetros de una función) mientras que `state` se administra *dentro* del componente (similar a las variables declaradas dentro de una función). |
16 | 16 |
|
17 |
| -Here are some good resources for further reading on when to use `props` vs `state`: |
| 17 | +Aquí hay algunos buenos recursos para leer más sobre cuándo usar `props` vs. `estado`: |
18 | 18 | * [Props vs State](https://github.com/uberVU/react-guide/blob/master/props-vs-state.md)
|
19 | 19 | * [ReactJS: Props vs. State](http://lucybain.com/blog/2016/react-state-vs-pros/)
|
20 | 20 |
|
21 |
| -### Why is `setState` giving me the wrong value? |
| 21 | +### ¿Por qué `setState` me está dando el valor incorrecto? |
22 | 22 |
|
23 |
| -In React, both `this.props` and `this.state` represent the *rendered* values, i.e. what's currently on the screen. |
| 23 | +En React, tanto `this.props` como `this.state` representan los valores *renderizados*, es decir, lo que hay actualmente en la pantalla. |
24 | 24 |
|
25 |
| -Calls to `setState` are asynchronous - don't rely on `this.state` to reflect the new value immediately after calling `setState`. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details). |
| 25 | +Las llamadas a `setState` son asíncronas; no te fíes de que `this.state` refleje el nuevo valor inmediatamente después de llamar a `setState`. Pasa una función de actualización en lugar de un objeto si necesitas calcular valores en función del estado actual (revisa a continuación para más detalles). |
26 | 26 |
|
27 |
| -Example of code that will *not* behave as expected: |
| 27 | +Ejemplo de código que *no* se comportará como se espera: |
28 | 28 |
|
29 | 29 | ```jsx
|
30 | 30 | incrementCount() {
|
31 |
| - // Note: this will *not* work as intended. |
| 31 | + // Nota: esto *no* funcionará como se espera. |
32 | 32 | this.setState({count: this.state.count + 1});
|
33 | 33 | }
|
34 | 34 |
|
35 | 35 | handleSomething() {
|
36 |
| - // Let's say `this.state.count` starts at 0. |
| 36 | + // Digamos que `this.state.count` se inicia en 0. |
37 | 37 | this.incrementCount();
|
38 | 38 | this.incrementCount();
|
39 | 39 | this.incrementCount();
|
40 |
| - // When React re-renders the component, `this.state.count` will be 1, but you expected 3. |
| 40 | + // Cuando React rerenderiza el componente, `this.state.count` será 1, pero tu esperabas 3. |
41 | 41 |
|
42 |
| - // This is because `incrementCount()` function above reads from `this.state.count`, |
43 |
| - // but React doesn't update `this.state.count` until the component is re-rendered. |
44 |
| - // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1. |
| 42 | + // Esto es porque la función anterior `incrementCount()` lee de `this.state.count`, |
| 43 | + // pero React no actualiza `this.state.count` hasta que el componente se vuelve a renderizar. |
| 44 | + // Entonces `incrementCount()` termina leyendo `this.state.count` como 0 cada vez, y lo establece a 1. |
45 | 45 |
|
46 |
| - // The fix is described below! |
| 46 | + // ¡La solución se describe a continuación! |
47 | 47 | }
|
48 | 48 | ```
|
49 | 49 |
|
50 |
| -See below for how to fix this problem. |
| 50 | +Ve a continuación cómo solucionar este problema. |
51 | 51 |
|
52 |
| -### How do I update state with values that depend on the current state? |
| 52 | +### ¿Cómo actualizo el estado con valores que dependen del estado actual? |
53 | 53 |
|
54 |
| -Pass a function instead of an object to `setState` to ensure the call always uses the most updated version of state (see below). |
| 54 | +Pasa una función en lugar de un objeto a `setState` para asegurarte de que la llamada siempre use la versión más actualizada del estado (ver más abajo). |
55 | 55 |
|
56 |
| -### What is the difference between passing an object or a function in `setState`? |
| 56 | +### ¿Cuál es la diferencia entre pasar un objeto o una función en `setState`? |
57 | 57 |
|
58 |
| -Passing an update function allows you to access the current state value inside the updater. Since `setState` calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting: |
| 58 | +Pasar una función de actualización te permite acceder al valor del estado actual dentro del actualizador. Dado que las llamadas a `setState` son por lotes, esto te permite encadenar actualizaciones y asegurarte de que se construyan una encima de otra en lugar de generar conflictos: |
59 | 59 |
|
60 | 60 | ```jsx
|
61 | 61 | incrementCount() {
|
62 | 62 | this.setState((state) => {
|
63 |
| - // Important: read `state` instead of `this.state` when updating. |
| 63 | + // Importante: lee `state` en vez de `this.state` al actualizar. |
64 | 64 | return {count: state.count + 1}
|
65 | 65 | });
|
66 | 66 | }
|
67 | 67 |
|
68 | 68 | handleSomething() {
|
69 |
| - // Let's say `this.state.count` starts at 0. |
| 69 | + // Digamos que `this.state.count` inicia en 0. |
70 | 70 | this.incrementCount();
|
71 | 71 | this.incrementCount();
|
72 | 72 | this.incrementCount();
|
73 | 73 |
|
74 |
| - // If you read `this.state.count` now, it would still be 0. |
75 |
| - // But when React re-renders the component, it will be 3. |
| 74 | + // Si lees `this.state.count` ahora, aún sería 0. |
| 75 | + // Pero cuando React vuelva a renderizar el componente, será 3. |
76 | 76 | }
|
77 | 77 | ```
|
78 | 78 |
|
79 |
| -[Learn more about setState](/docs/react-component.html#setstate) |
| 79 | +[Aprende más sobre setState](/docs/react-component.html#setstate) |
80 | 80 |
|
81 |
| -### When is `setState` asynchronous? |
| 81 | +### ¿Cuándo `setState` es asíncrono? |
82 | 82 |
|
83 |
| -Currently, `setState` is asynchronous inside event handlers. |
| 83 | +Actualmente, `setState` es asíncrono dentro de los controladores de eventos. |
84 | 84 |
|
85 |
| -This ensures, for example, that if both `Parent` and `Child` call `setState` during a click event, `Child` isn't re-rendered twice. Instead, React "flushes" the state updates at the end of the browser event. This results in significant performance improvements in larger apps. |
| 85 | +Esto garantiza, por ejemplo, que si `Parent` y `Child` llaman a `setState` durante un evento de click, `Child` no se renderiza dos veces. En su lugar, React "vacía" las actualizaciones del estado al final del evento del navegador. Esto se traduce en mejoras significativas de rendimiento en aplicaciones más grandes. |
86 | 86 |
|
87 |
| -This is an implementation detail so avoid relying on it directly. In the future versions, React will batch updates by default in more cases. |
| 87 | +Este es un detalle de implementación, así que evita confiar en él directamente. En las versiones futuras, React realizará actualizaciones por lotes por defecto en más casos. |
88 | 88 |
|
89 |
| -### Why doesn't React update `this.state` synchronously? |
| 89 | +### ¿Por qué React no actualiza `this.state` de forma sincrónica? |
90 | 90 |
|
91 |
| -As explained in the previous section, React intentionally "waits" until all components call `setState()` in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders. |
| 91 | +Como se explicó en la sección anterior, React intencionalmente "espera" hasta que todos los componentes llamen a `setState()` en sus controladores de eventos antes de comenzar a rerenderizar. Esto aumenta el rendimiento al evitar rerenderizados innecesarios. |
92 | 92 |
|
93 |
| -However, you might still be wondering why React doesn't just update `this.state` immediately without re-rendering. |
| 93 | +Sin embargo, es posible que aún te estés preguntando por qué React no solo actualiza 'this.state' inmediatamente sin volver a renderizar. |
94 | 94 |
|
95 |
| -There are two main reasons: |
| 95 | +Hay dos razones principales: |
96 | 96 |
|
97 |
| -* This would break the consistency between `props` and `state`, causing issues that are very hard to debug. |
98 |
| -* This would make some of the new features we're working on impossible to implement. |
| 97 | +* Esto rompería la consistencia entre `props` y `state`, causando problemas que son muy difíciles de depurar. |
| 98 | +* Esto haría que algunas de las nuevas funcionalidades en las que estamos trabajando sean imposibles de implementar. |
99 | 99 |
|
100 |
| -This [GitHub comment](https://github.com/facebook/react/issues/11527#issuecomment-360199710) dives deep into the specific examples. |
| 100 | +Este [comentario de GitHub](https://github.com/facebook/react/issues/11527#issuecomment-360199710) profundiza en los ejemplos específicos. |
101 | 101 |
|
102 |
| -### Should I use a state management library like Redux or MobX? |
| 102 | +### ¿Debo usar una biblioteca de manejo de estado como Redux o MobX? |
103 | 103 |
|
104 |
| -[Maybe.](https://redux.js.org/faq/general#when-should-i-use-redux) |
| 104 | +[Tal vez.](https://redux.js.org/faq/general#when-should-i-use-redux) |
105 | 105 |
|
106 |
| -It's a good idea to get to know React first, before adding in additional libraries. You can build quite complex applications using only React. |
| 106 | +Es una buena idea conocer primero React, antes de agregar bibliotecas adicionales. Puedes construir aplicaciones bastante complejas usando solo React. |
0 commit comments