Skip to content

Commit b2d481d

Browse files
Merge pull request #126 from d4vsanchez/master
Translate: Strict mode
2 parents 2235567 + 86c4520 commit b2d481d

File tree

2 files changed

+59
-58
lines changed

2 files changed

+59
-58
lines changed

content/docs/addons-test-utils.md

+6-5
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ var ReactTestUtils = require('react-dom/test-utils'); // ES5 with npm
4444

4545
### `act()` {#act}
4646

47-
Para preparar un componente en ser asegurado, debes envolver el código que lo renderiza y que realiza actualizaciones sobre este en un llamado a `act()`. Esto hace que tus pruebas corran de una forma más parecida a como lo hace React en el navegador.
47+
Para preparar la asertividad en un componente, debes envolver el código que lo renderiza y que realiza actualizaciones sobre este en un llamado a `act()`. Esto hace que tus pruebas corran de una forma más parecida a como lo hace React en el navegador.
4848

4949
>Nota
5050
>
@@ -122,7 +122,7 @@ it('can render and update a counter', () => {
122122
});
123123
```
124124

125-
No olvides que la ejecución de eventos del DOM sólo funciona cuando el contenedor del DOM es agregado al `document`. Puedes utilizar una ayuda como [`react-testing-library`](https://github.com/kentcdodds/react-testing-library) para reducir todo el código repetitivo.
125+
No olvides que la ejecución de eventos del DOM sólo funciona cuando el contenedor del DOM es agregado al `document`. Puedes utilizar un ayudante como [`react-testing-library`](https://github.com/kentcdodds/react-testing-library) para reducir todo el código repetitivo.
126126

127127
* * *
128128

@@ -322,7 +322,7 @@ Simulate.{eventName}(
322322

323323
Simula la ejecución de un evento en un nodo del DOM con los datos de evento `eventData` opcionales.
324324

325-
`Simulate` tiene un método para [cada uno de los eventos que React comprende](/docs/events.html#supported-events).
325+
`Simulate` tiene un método para [cada uno de los eventos que React entiende](/docs/events.html#supported-events).
326326

327327
**Haciendo clic en un elemento**
328328

@@ -332,7 +332,7 @@ const node = this.button;
332332
ReactTestUtils.Simulate.click(node);
333333
```
334334

335-
**Cambiar el valor en un campo de entrada y presionar ENTER.**
335+
**Cambiando el valor en un campo de entrada y presionando ENTER.**
336336

337337
```javascript
338338
// <input ref={(node) => this.textInput = node} />
@@ -343,6 +343,7 @@ ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
343343
```
344344

345345
> Nota
346-
> Se debe proveer cualquiera de las propiedades del evento que se esté usando en tu componente (p.e. keyCode, which, etc...) ya que React no creará ninguna de estas por ti.
346+
>
347+
> Tendrás que proveer cualquiera de las propiedades del evento que se esté usando en tu componente (p.e. keyCode, which, etc...) ya que React no creará ninguna de estas por ti.
347348
348349
* * *

content/docs/strict-mode.md

+53-53
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,65 @@
11
---
22
id: strict-mode
3-
title: Strict Mode
3+
title: Modo estricto
44
permalink: docs/strict-mode.html
55
---
66

7-
`StrictMode` is a tool for highlighting potential problems in an application. Like `Fragment`, `StrictMode` does not render any visible UI. It activates additional checks and warnings for its descendants.
7+
`StrictMode` es una herramienta para destacar problemas potenciales en la aplicación. Al igual que `Fragment`, `StrictMode` no renderiza nada en la UI. Este modo también activa advertencias y comprobaciones adicionales para sus descendientes.
88

9-
> Note:
9+
> Nota:
1010
>
11-
> Strict mode checks are run in development mode only; _they do not impact the production build_.
11+
> Las comprobaciones hechas por el modo estricto solamente son ejecutadas en el modo de desarrollo; _no van a impactar producción_.
1212
13-
You can enable strict mode for any part of your application. For example:
13+
Puedes habilitar el modo estricto para cualquier parte de tu aplicación. Por ejemplo:
1414
`embed:strict-mode/enabling-strict-mode.js`
1515

16-
In the above example, strict mode checks will *not* be run against the `Header` and `Footer` components. However, `ComponentOne` and `ComponentTwo`, as well as all of their descendants, will have the checks.
16+
En el ejemplo anterior, las comprobaciones del modo estricto *no* va a correr en los componentes de `Header` y `Footer`. Sin embargo, `ComponentOne` y `ComponentTwo`, así como todos sus descendientes, tendrán las comprobaciones.
1717

18-
`StrictMode` currently helps with:
19-
* [Identifying components with unsafe lifecycles](#identifying-unsafe-lifecycles)
20-
* [Warning about legacy string ref API usage](#warning-about-legacy-string-ref-api-usage)
21-
* [Warning about deprecated findDOMNode usage](#warning-about-deprecated-finddomnode-usage)
22-
* [Detecting unexpected side effects](#detecting-unexpected-side-effects)
23-
* [Detecting legacy context API](#detecting-legacy-context-api)
18+
`StrictMode` en la actualidad ayuda a:
19+
* [Identificar ciclos de vida inseguros](#identifying-unsafe-lifecycles)
20+
* [Advertencia sobre el uso de la API legado de string ref](#warning-about-legacy-string-ref-api-usage)
21+
* [Advertencia sobre el uso del método obsoleto findDOMNode](#warning-about-deprecated-finddomnode-usage)
22+
* [Detectar efectos secundarios inesperados](#detecting-unexpected-side-effects)
23+
* [Detectar el uso de la API legado para el contexto](#detecting-legacy-context-api)
2424

25-
Additional functionality will be added with future releases of React.
25+
Funcionalidades adicionales serán agregadas en futuras versiones de React.
2626

27-
### Identifying unsafe lifecycles {#identifying-unsafe-lifecycles}
27+
### Identificar ciclos de vida inseguros {#identifying-unsafe-lifecycles}
2828

29-
As explained [in this blog post](/blog/2018/03/27/update-on-async-rendering.html), certain legacy lifecycle methods are unsafe for use in async React applications. However, if your application uses third party libraries, it can be difficult to ensure that these lifecycles aren't being used. Fortunately, strict mode can help with this!
29+
Como fue explicado [en este artículo del blog](/blog/2018/03/27/update-on-async-rendering.html), algúnos cíclos de vida antiguos son inseguros para ser usados en aplicaciones de React asíncronas. Sin embargo, si tu aplicación utiliza librerías de terceros, puede ser díficil asegurar que estos ciclos de vida no estén siendo utilizados. Por fortuna, ¡el modo estricto puede ayudar con esto!
3030

31-
When strict mode is enabled, React compiles a list of all class components using the unsafe lifecycles, and logs a warning message with information about these components, like so:
31+
Cuando el modo estricto está habilitado, React reune en una lista todos los componentes de clases que están usando ciclos de vida inseguros, y registra por medio de un mensaje de advertencia la información sobre estos componentes, de esta forma:
3232

3333
![](../images/blog/strict-mode-unsafe-lifecycles-warning.png)
3434

35-
Addressing the issues identified by strict mode _now_ will make it easier for you to take advantage of async rendering in future releases of React.
35+
Solucionar los problemas identificados por el modo estricto _ahora_, hará que sea más fácil para ti aprovechar el renderizamiento asíncrono en futuras versiones de React.
3636

37-
### Warning about legacy string ref API usage {#warning-about-legacy-string-ref-api-usage}
37+
### Advertencia sobre el uso de la API legado de string ref {#warning-about-legacy-string-ref-api-usage}
3838

39-
Previously, React provided two ways for managing refs: the legacy string ref API and the callback API. Although the string ref API was the more convenient of the two, it had [several downsides](https://github.com/facebook/react/issues/1373) and so our official recommendation was to [use the callback form instead](/docs/refs-and-the-dom.html#legacy-api-string-refs).
39+
Anteriormente, React proporcionaba dos formas para utilizar refs: la API legado de string ref y la API por callback. Aunque la API de string ref era la más cómoda de las dos, tenía [muchas desventajas](https://github.com/facebook/react/issues/1373) y por lo tanto nuestra recomendación oficial fue [usar la forma de callback en su lugar](/docs/refs-and-the-dom.html#legacy-api-string-refs)
4040

41-
React 16.3 added a third option that offers the convenience of a string ref without any of the downsides:
41+
React 16.3 agregó una tercera opción que ofrece la comodidad que tiene string ref sin ninguna de las desventajas:
4242
`embed:16-3-release-blog-post/create-ref-example.js`
4343

44-
Since object refs were largely added as a replacement for string refs, strict mode now warns about usage of string refs.
44+
Desde que los object refs fueron agregados en gran parte como reemplazo a los string refs, el modo estricto ahora advierte sobre el uso de string refs.
4545

46-
> **Note:**
46+
> **Nota:**
4747
>
48-
> Callback refs will continue to be supported in addition to the new `createRef` API.
48+
> Los callback refs seguirán siendo soportados en conjunto con la nueva API de `createRef`.
4949
>
50-
> You don't need to replace callback refs in your components. They are slightly more flexible, so they will remain as an advanced feature.
50+
> No necesitas reemplazar los callback refs en tu componente. Son un poco más flexibles, por lo que continuarán estando como una característica avanzada.
5151
52-
[Learn more about the new `createRef` API here.](/docs/refs-and-the-dom.html)
52+
[Aprende más sobre la API `createRef` aquí.](/docs/refs-and-the-dom.html)
5353

54-
### Warning about deprecated findDOMNode usage {#warning-about-deprecated-finddomnode-usage}
54+
### Advertencia sobre el uso del método obsoleto findDOMNode {#warning-about-deprecated-finddomnode-usage}
5555

56-
React used to support `findDOMNode` to search the tree for a DOM node given a class instance. Normally you don't need this because you can [attach a ref directly to a DOM node](/docs/refs-and-the-dom.html#creating-refs).
56+
React solía soportar `findDOMNode` para buscar en el árbol un nodo del DOM dada una instancia de una clase. Normalmente no necesitas hacer esto ya que puedes [vincular un ref directamente un nodo del DOM](/docs/refs-and-the-dom.html#creating-refs).
5757

58-
`findDOMNode` can also be used on class components but this was breaking abstraction levels by allowing a parent to demand that certain children was rendered. It creates a refactoring hazard where you can't change the implementation details of a component because a parent might be reaching into its DOM node. `findDOMNode` only returns the first child, but with the use of Fragments, it is possible for a component to render multiple DOM nodes. `findDOMNode` is a one time read API. It only gave you an answer when you asked for it. If a child component renders a different node, there is no way to handle this change. Therefore `findDOMNode` only worked if components always return a single DOM node that never changes.
58+
`findDOMNode`también puede ser utilizado en componentes con clases pero esto estaba dañando los niveles de abstracción al permitir a un padre solicitar que cierto hijo fuera renderizado. Esto crea un peligro para refactorizar algo en el caso que no puedas cambiar los detalles de la implementación de un componente ya que un padre puede estar utilizando uno de sus nodos del DOM. `findDOMNode` sólo retorna el primer hijo, pero con el uso de los Fragmentos, es posible que un componente pueda renderizar múltiples nodos del DOM. `findDOMNode` es una API de solo lectura para usar una sola vez. Sólo da una respuesta cuando se invoca el método. Si un componente hijo renderiza un nodo diferente, no hay forma alguna de manipular este cambio. Por lo tanto `findDOMNode` solo funciona si los componentes simpre retornan un solo nodo de DOM que nunca cambie.
5959

60-
You can instead make this explicit by pass a ref to your custom component and pass that along to the DOM using [ref forwarding](/docs/forwarding-refs.html#forwarding-refs-to-dom-components).
60+
En su lugar puedes hacer que este comportamiento sea explicito pasando un ref a tu componente personalizado y transmitiendolo al DOM usando el [reenvio de ref](/docs/forwarding-refs.html#forwarding-refs-to-dom-components).
6161

62-
You can also add a wrapper DOM node in your component and attach a ref directly to it.
62+
También puedes agregar un nodo del DOM envuelto en tu componente y vincular un ref directamente al mismo.
6363

6464
```javascript{4,7}
6565
class MyComponent extends React.Component {
@@ -73,52 +73,52 @@ class MyComponent extends React.Component {
7373
}
7474
```
7575

76-
> Note:
76+
> Nota:
7777
>
78-
> In CSS, the [`display: contents`](https://developer.mozilla.org/en-US/docs/Web/CSS/display#display_contents) attribute can be used if you don't want the node to be part of the layout.
78+
> En CSS, el atributo [`display: contents`](https://developer.mozilla.org/en-US/docs/Web/CSS/display#display_contents) puede ser usado si no quieres que el nodo sea parte de la estructura.
7979
80-
### Detecting unexpected side effects {#detecting-unexpected-side-effects}
80+
### Detectar efectos secundarios inesperados {#detecting-unexpected-side-effects}
8181

82-
Conceptually, React does work in two phases:
83-
* The **render** phase determines what changes need to be made to e.g. the DOM. During this phase, React calls `render` and then compares the result to the previous render.
84-
* The **commit** phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like `componentDidMount` and `componentDidUpdate` during this phase.
82+
Conceptualmente, React funciona en dos fases:
83+
* La fase de **renderizado** determina que cambios deben ser hechos a p.ej. el DOM. Durante esta fase, React llama a `render` y compara su resultado con los del renderizado anterior.
84+
* La fase de **confirmación** es aquella donde React aplica cualquiera de los cambios. (En el caso de React en el DOM, esto es cuando React inserta, actualiza y remueve nodos del DOM.) React también llama ciclos de vida tales como `componentDidMount` y `componentDidUpdate` durante esta fase.
8585

86-
The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming async mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).
86+
La fase de **confirmación** es muy rápida generalmente, pero el renderizado puede ser lento. Por esta razón, el próximo modo asíncrono (que no está habilitado por defecto aún) separa el trabajo de renderizado en diferentes etapas, pausando y reanudando el trabajo para prevenir bloquear el navegador. Esto significa que React puede que invoque los ciclos de vida presentes en la fase de renderizado múltiples veces antes de terminar la confirmación, o puede invocarlos todos sin terminar la confirmación (porque ocurrió algún error o una interrupción de alta prioridad).
8787

88-
Render phase lifecycles include the following class component methods:
88+
El ciclo de vida de la fase de renderizado incluye los siguientes métodos de los componentes en clases:
8989
* `constructor`
9090
* `componentWillMount`
9191
* `componentWillReceiveProps`
9292
* `componentWillUpdate`
9393
* `getDerivedStateFromProps`
9494
* `shouldComponentUpdate`
9595
* `render`
96-
* `setState` updater functions (the first argument)
96+
* Funciones de actualización de `setState` (el primer argumento)
9797

98-
Because the above methods might be called more than once, it's important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be [non-deterministic](https://en.wikipedia.org/wiki/Deterministic_algorithm).
98+
Ya que los métodos arriba mencionados pueden ser llamados más de una vez, es importante que estos no contengan ningún efecto secundario. Ignorar esta regla puede llevar a una cantidad de problemas, incluyendo fugas de memoria y estados de aplicación inválido. Desafortunadamente, puede ser muy difícil el detectar estos problemas ya con frecuencia pueden ser [no determinísticos](https://en.wikipedia.org/wiki/Deterministic_algorithm).
9999

100-
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:
100+
El modo estricto no puede detectar efectos secundarios de forma automática por ti, pero te puede ayudar a encontrarlos al hacerlos un poco más determinísticos. Esto se logra al invocar dos veces los siguientes métodos:
101101

102-
* Class component `constructor` method
103-
* The `render` method
104-
* `setState` updater functions (the first argument)
105-
* The static `getDerivedStateFromProps` lifecycle
102+
* El método `constructor` en los componentes de clases
103+
* El método `render`
104+
* Funciones de actualización de `setState` (el primer argumento)
105+
* El ciclo de vida estático `getDerivedStateFromProps`
106106

107-
> Note:
107+
> Nota:
108108
>
109-
> This only applies to development mode. _Lifecycles will not be double-invoked in production mode._
109+
> Esto solo aplica al modo de desarrollo. _Los ciclos de vida no serán invocados dos veces en el modo de producción._
110110
111-
For example, consider the following code:
111+
Por ejemplo, considera el siguiente código:
112112
`embed:strict-mode/side-effects-in-constructor.js`
113113

114-
At first glance, this code might not seem problematic. But if `SharedApplicationState.recordEvent` is not [idempotent](https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning), then instantiating this component multiple times could lead to invalid application state. This sort of subtle bug might not manifest during development, or it might do so inconsistently and so be overlooked.
114+
En primera instancia, este código no debería parecer problemático. Pero si `SharedApplicationState.recordEvent` no es [idempotente](https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning), entonces al instanciar este componente múltiples veces puede llevar a que tenga un estado de aplicación inválido. Estos tipo de bug sutiles pueden no manifestarse durante el desarrollo, o quizas sí lo hagan pero de forma inconsistente y se pase por alto.
115115

116-
By intentionally double-invoking methods like the component constructor, strict mode makes patterns like this easier to spot.
116+
Al invocar los métodos dos veces, como el constructor del componente, el modo estricto hace que patrones como estos sean más fáciles de encontrar.
117117

118-
### Detecting legacy context API {#detecting-legacy-context-api}
118+
### Detectar el uso de la API legado para el contexto {#detecting-legacy-context-api}
119119

120-
The legacy context API is error-prone, and will be removed in a future major version. It still works for all 16.x releases but will show this warning message in strict mode:
120+
La API legado para el contexto es propensa a errores, y será eliminada en una versión principal a futuro. Aún está funcionando para todas las versiones 16.x pero mostrará el siguiente mensaje de advertencia si se usa en modo estricto:
121121

122122
![](../images/blog/warn-legacy-context-in-strict-mode.png)
123123

124-
Read the [new context API documentation](/docs/context.html) to help migrate to the new version.
124+
Lee sobre la [nueva documentación de la API de contexto](/docs/context.html) para ayudarte a migrar a la nueva versión.

0 commit comments

Comments
 (0)