Skip to content

Commit

Permalink
Merge pull request #81 from jvelezpo/more-warnings
Browse files Browse the repository at this point in the history
More warnings
  • Loading branch information
alejandronanez committed Feb 7, 2019
2 parents 71d889c + 3b5fa8f commit b713a7b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 45 deletions.
45 changes: 23 additions & 22 deletions content/warnings/dont-call-proptypes.md
Expand Up @@ -4,64 +4,64 @@ layout: single
permalink: warnings/dont-call-proptypes.html
---

> Note:
> Nota:
>
> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types).
> `React.PropTypes` se ha mudado a un paquete diferente desde React v15.5. Utiliza [la biblioteca `prop-types` en su lugar](https://www.npmjs.com/package/prop-types).
>
>We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) to automate the conversion.
> Proporcionamos [un script codemod](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) para automatizar la conversión.
In a future major release of React, the code that implements PropType validation functions will be stripped in production. Once this happens, any code that calls these functions manually (that isn't stripped in production) will throw an error.
En una importante versión futura de React, el código que implementa las funciones de validación PropType se eliminará en producción. Una vez que esto suceda, cualquier código que llame a estas funciones manualmente (que no se haya eliminado en producción) generará un error.

### Declaring PropTypes is still fine
### Declarar PropTypes todavía está bien

The normal usage of PropTypes is still supported:
El uso normal de PropTypes todavía es compatible:

```javascript
Button.propTypes = {
highlighted: PropTypes.bool
};
```

Nothing changes here.
Nada cambia aquí.

### Don’t call PropTypes directly
### No llames PropTypes directamente

Using PropTypes in any other way than annotating React components with them is no longer supported:
Ya no se admite el uso de PropTypes de otra manera que no sea la anotación de componentes React con ellos:

```javascript
var apiShape = PropTypes.shape({
body: PropTypes.object,
statusCode: PropTypes.number.isRequired
}).isRequired;

// Not supported!
// ¡No soportado!
var error = apiShape(json, 'response');
```

If you depend on using PropTypes like this, we encourage you to use or create a fork of PropTypes (such as [these](https://github.com/aackerman/PropTypes) [two](https://github.com/developit/proptypes) packages).
Si dependes en el uso de PropTypes como este, te recomendamos que uses o crees una bifurcación de PropTypes (como [estos](https://github.com/aackerman/PropTypes) [dos](https://github.com/developit/proptypes) paquetes).

If you don't fix the warning, this code will crash in production with React 16.
Si no corriges la advertencia, este código se bloqueará en la versión de producción que use React 16.

### If you don't call PropTypes directly but still get the warning
### Si no llamas directamente a PropTypes pero sigues recibiendo la advertencia

Inspect the stack trace produced by the warning. You will find the component definition responsible for the PropTypes direct call. Most likely, the issue is due to third-party PropTypes that wrap React’s PropTypes, for example:
Inspecciona la traza producida por la advertencia. Encontrarás la definición del componente responsable de la llamada directa PropTypes. Probablemente, el problema se deba a PropTypes de terceros que envuelven PropTypes de React, por ejemplo:

```js
Button.propTypes = {
highlighted: ThirdPartyPropTypes.deprecated(
PropTypes.bool,
'Use `active` prop instead'
'Usa prop `active` en su lugar'
)
}
```

In this case, `ThirdPartyPropTypes.deprecated` is a wrapper calling `PropTypes.bool`. This pattern by itself is fine, but triggers a false positive because React thinks you are calling PropTypes directly. The next section explains how to fix this problem for a library implementing something like `ThirdPartyPropTypes`. If it's not a library you wrote, you can file an issue against it.
En este caso, `ThirdPartyPropTypes.deprecated` es un contenedor que llama a `PropTypes.bool`. Este patrón en sí mismo está bien, pero desencadena un falso positivo porque React cree que tú estás llamando directamente a PropTypes. La siguiente sección explica cómo solucionar este problema para una biblioteca que implementa algo como `ThirdPartyPropTypes`. Si no es una biblioteca que escribiste, puedes abrir un issue en su proyecto.

### Fixing the false positive in third party PropTypes
### Solucionando el falso positivo en PropTypes de terceros

If you are an author of a third party PropTypes library and you let consumers wrap existing React PropTypes, they might start seeing this warning coming from your library. This happens because React doesn't see a "secret" last argument that [it passes](https://github.com/facebook/react/pull/7132) to detect manual PropTypes calls.
Si tú eres autor de una biblioteca PropTypes y dejas que los consumidores envuelvan los PropTypes React existentes, es posible que comiencen a ver esta advertencia proveniente de su biblioteca. Esto sucede porque React no ve un último argumento "secreto" que [se pasa](https://github.com/facebook/react/pull/7132) para detectar llamadas de PropTypes manuales.

Here is how to fix it. We will use `deprecated` from [react-bootstrap/react-prop-types](https://github.com/react-bootstrap/react-prop-types/blob/0d1cd3a49a93e513325e3258b28a82ce7d38e690/src/deprecated.js) as an example. The current implementation only passes down the `props`, `propName`, and `componentName` arguments:
Aquí esta cómo solucionarlo. Usaremos `deprecated` de [react-bootstrap/react-prop-types](https://github.com/react-bootstrap/react-prop-types/blob/0d1cd3a49a93e513325e3258b28a82ce7d38e690/src/deprecated.js) como un ejemplo. La implementación actual sólo pasa los argumentos `props`,`propName` y `componentName`:

```javascript
export default function deprecated(propType, explanation) {
Expand All @@ -80,10 +80,11 @@ export default function deprecated(propType, explanation) {
```

In order to fix the false positive, make sure you pass **all** arguments down to the wrapped PropType. This is easy to do with the ES6 `...rest` notation:
Para corregir el falso positivo, asegurate de pasar **todos** los argumentos al PropType envuelto. Esto es fácil de hacer con la notación ES6 `...rest`:

```javascript
export default function deprecated(propType, explanation) {
return function validate(props, propName, componentName, ...rest) { // Note ...rest here
return function validate(props, propName, componentName, ...rest) { // Nota ...rest aqui
if (props[propName] != null) {
const message = `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`;
if (!warned[message]) {
Expand All @@ -92,9 +93,9 @@ export default function deprecated(propType, explanation) {
}
}

return propType(props, propName, componentName, ...rest); // and here
return propType(props, propName, componentName, ...rest); // y aqui
};
}
```

This will silence the warning.
Esto silenciará la advertencia.
6 changes: 3 additions & 3 deletions content/warnings/invalid-aria-prop.md
Expand Up @@ -4,8 +4,8 @@ layout: single
permalink: warnings/invalid-aria-prop.html
---

The invalid-aria-prop warning will fire if you attempt to render a DOM element with an aria-* prop that does not exist in the Web Accessibility Initiative (WAI) Accessible Rich Internet Application (ARIA) [specification](https://www.w3.org/TR/wai-aria-1.1/#states_and_properties).
La advertencia invalid-aria-prop se activará si intentas renderizar un elemento DOM con un aria-* prop que no existe en la Iniciativa de accesibilidad web (WAI) Aplicación de Internet enriquecida accesible (ARIA) [especificación](https://www.w3.org/TR/wai-aria-1.1/#states_and_properties).

1. If you feel that you are using a valid prop, check the spelling carefully. `aria-labelledby` and `aria-activedescendant` are often misspelled.
1. Si sientes que estás utilizando un prop válido, revisa la ortografía cuidadosamente. `aria-labelledby` y` aria-activedescendant` a menudo están mal escritas.

2. React does not yet recognize the attribute you specified. This will likely be fixed in a future version of React. However, React currently strips all unknown attributes, so specifying them in your React app will not cause them to be rendered
2. React aún no reconoce el atributo que has especificado. Esto probablemente se solucionará en una versión futura de React. Sin embargo, React actualmente elimina todos los atributos desconocidos, por lo que especificarlos en su aplicación React no hará que se renderizen
41 changes: 21 additions & 20 deletions content/warnings/refs-must-have-owner.md
Expand Up @@ -4,45 +4,46 @@ layout: single
permalink: warnings/refs-must-have-owner.html
---

You are probably here because you got one of the following error messages:
Probablemente estés aquí porque recibió uno de los siguientes mensajes de error:

*React 16.0.0+*
> Warning:
> Advertencia:
>
> Element ref was specified as a string (myRefName) but no owner was set. You may have multiple copies of React loaded. (details: https://fb.me/react-refs-must-have-owner).
*earlier versions of React*
> Warning:
*versiones anteriores de React*
> Advertencia:
>
> addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded.
> addComponentAsRefTo(...): solo un ReactOwner puede tener refs. Es posible que esté agregando un ref a un componente que no se creó dentro del método `render` de un componente, o si tiene varias copias cargadas de React.
This usually means one of three things:
Esto usualmente significa una de tres cosas:

- You are trying to add a `ref` to a function component.
- You are trying to add a `ref` to an element that is being created outside of a component's render() function.
- You have multiple (conflicting) copies of React loaded (eg. due to a misconfigured npm dependency)
- Estás intentando agregar un `ref` a un componente de función.
- Está intentando agregar un `ref` a un elemento que se está creando fuera de la función render() de un componente.
- Tiene varias copias (en conflicto) de React cargadas (por ejemplo, debido a una dependencia npm mal configurada)

## Refs on Function Components
## Refs en los componentes de función

If `<Foo>` is a function component, you can't add a ref to it:
Si `<Foo>` es un componente de función, no puedes agregarle una referencia:

```js
// Doesn't work if Foo is a function!
// ¡No funciona si Foo es una función!
<Foo ref={foo} />
```

If you need to add a ref to a component, convert it to a class first, or consider not using refs as they are [rarely necessary](/docs/refs-and-the-dom.html#when-to-use-refs).
Si necesitas agregar una referencia a un componente, primero conviértelo a una clase, o considera no usar las referencias ya que son [raramente necesarias](/docs/refs-and-the-dom.html#when-to-use-refs).

## Strings Refs Outside the Render Method
## Cadenas de Ref fuera del método Render

This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). For example, this won't work:
Esto generalmente significa que estás intentando agregar una referencia a un componente que no tiene un propietario (es decir, no se creó dentro del método `render` de otro componente). Por ejemplo, esto no funcionará:

```js
// Doesn't work!
// ¡No funciona!
ReactDOM.render(<App ref="app" />, el);
```

Try rendering this component inside of a new top-level component which will hold the ref. Alternatively, you may use a callback ref:
Intenta renderizar este componente dentro de un nuevo componente de nivel superior que contendrá la referencia. Como alternativa, puedes utilizar una referencia de callback:

```js
let app;
Expand All @@ -54,10 +55,10 @@ ReactDOM.render(
);
```

Consider if you [really need a ref](/docs/refs-and-the-dom.html#when-to-use-refs) before using this approach.
Considera si [realmente necesitas una referencia](/docs/refs-and-the-dom.html#when-to-use-refs) antes de usar este enfoque.

## Multiple copies of React
## Múltiples copias de React

Bower does a good job of deduplicating dependencies, but npm does not. If you aren't doing anything (fancy) with refs, there is a good chance that the problem is not with your refs, but rather an issue with having multiple copies of React loaded into your project. Sometimes, when you pull in a third-party module via npm, you will get a duplicate copy of the dependency library, and this can create problems.
Bower hace un buen trabajo de deduplicación de dependencias, pero npm no lo hace. Si no está haciendo nada (elegante) con refs, hay una buena probabilidad de que el problema no sea con sus refs, sino más bien un problema con tener varias copias de React cargadas en tu proyecto. A veces, cuando ingresa un módulo de terceros a través de npm, obtendrás una copia duplicada de la biblioteca de dependencias, y esto puede crear problemas.

If you are using npm... `npm ls` or `npm ls react` might help illuminate.
Si estás utilizando npm... `npm ls` o `npm ls react` pueden ayudarte a iluminarte.

0 comments on commit b713a7b

Please sign in to comment.