You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/hooks-reference.md
+1-47Lines changed: 1 addition & 47 deletions
Original file line number
Diff line number
Diff line change
@@ -6,11 +6,7 @@ prev: hooks-custom.html
6
6
next: hooks-faq.html
7
7
---
8
8
9
-
<<<<<<< HEAD
10
-
Los *Hooks* son una próxima característica que te permite usar el estado y otras características de React sin escribir una clase. Están actualmente en React v16.8.0-alpha.1.
11
-
=======
12
9
*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
13
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
14
10
15
11
Esta página describe las API para los Hooks incorporados en React.
16
12
@@ -83,11 +79,7 @@ Los botones "+" y "-" usan la forma funcional, porque el valor actualizado se ba
83
79
>
84
80
> Otra opción es `useReducer`, que es más adecuada para administrar objetos de estado que contienen múltiples subvalores.
85
81
86
-
<<<<<<< HEAD
87
82
#### Inicialización gradual
88
-
=======
89
-
#### Lazy initial state
90
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
91
83
92
84
El argumento `initialState` es el estado utilizado durante el render inicial. En renders posteriores, se ignora. Si el estado inicial es el resultado de un cálculo costoso, puede proporcionar una función en su lugar, que se ejecutará solo en el render inicial:
Una alternativa a [`useState`](#usestate). Acepta un reducer de tipo `(state, action) => newState` y devuelve el estado actual emparejado con un método` dispatch`. (Si está familiarizado con Redux, ya sabe cómo funciona).
192
184
193
-
<<<<<<< HEAD
194
-
Aquí está el ejemplo de contador de la sección [`useState`] (# usestate), reescrito para usar un reducer:
195
-
=======
196
185
`useReducer` is usually preferable to `useState` when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. `useReducer` also lets you optimize performance for components that trigger deep updates because [you can pass `dispatch` down instead of callbacks](/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down).
197
186
198
187
Here's the counter example from the [`useState`](#usestate) section, rewritten to use a reducer:
199
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
200
188
201
189
```js
202
190
constinitialState= {count:0};
@@ -208,13 +196,7 @@ function reducer(state, action) {
208
196
case'decrement':
209
197
return {count:state.count-1};
210
198
default:
211
-
<<<<<<<HEAD
212
-
// Un reducer siempre debe devolver un estado válido.
213
-
// Alternativamente, puede lanzar un error si se envía una acción no válida.
214
-
return state;
215
-
=======
216
199
thrownewError();
217
-
>>>>>>>98c1d22fbef2638cafb03b07e0eabe2a6186fca8
218
200
}
219
201
}
220
202
@@ -230,11 +212,6 @@ function Counter({initialCount}) {
230
212
}
231
213
```
232
214
233
-
<<<<<<< HEAD
234
-
#### Inicialización diferida
235
-
236
-
`useReducer` acepta un tercer argumento opcional, `initialAction`. Si se proporciona, la acción inicial se aplica durante el render inicial. Esto es útil para calcular un estado inicial que incluye valores pasados a través de props:
237
-
=======
238
215
#### Specifying the initial state
239
216
240
217
There’s two different ways to initialize `useReducer` state. You may choose either one depending on the use case. The simplest way to pass the initial state as a second argument:
@@ -253,7 +230,6 @@ There’s two different ways to initialize `useReducer` state. You may choose ei
253
230
#### Lazy initialization
254
231
255
232
You can also create the initial state lazily. To do this, you can pass an `init` function as the third argument. The initial state will be set to `init(initialArg)`.
256
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
257
233
258
234
It lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action:
259
235
@@ -409,25 +385,16 @@ useDebugValue(value)
409
385
410
386
`useDebugValue` puede usarse para mostrar una etiqueta para Hooks personalizados en React DevTools.
411
387
412
-
<<<<<<< HEAD
413
-
Por ejemplo, considere el Hook personalizado `useFriendStatus` descrito en ["Construyendo sus propios Hooks"](/docs/hooks-custom.html):
414
-
=======
415
-
For example, consider the `useFriendStatus` custom Hook described in ["Building Your Own Hooks"](/docs/hooks-custom.html):
416
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
388
+
Por ejemplo, considera el Hook personalizado `useFriendStatus` descrito en ["Construyendo sus propios Hooks"](/docs/hooks-custom.html):
417
389
418
390
```js{6-8}
419
391
function useFriendStatus(friendID) {
420
392
const [isOnline, setIsOnline] = useState(null);
421
393
422
394
// ...
423
395
424
-
<<<<<<< HEAD
425
396
// Mostrar una etiqueta en DevTools junto a este Hook
426
397
// por ejemplo: "FriendStatus: Online"
427
-
=======
428
-
// Show a label in DevTools next to this Hook
429
-
// e.g. "FriendStatus: Online"
430
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
431
398
useDebugValue(isOnline ? 'Online' : 'Offline');
432
399
433
400
return isOnline;
@@ -436,28 +403,15 @@ function useFriendStatus(friendID) {
436
403
437
404
> Consejo
438
405
>
439
-
<<<<<<< HEAD
440
406
> No recomendamos agregar valores de depuración a cada Hook personalizado. Es más valioso para los Hooks personalizados que forman parte de las bibliotecas compartidas.
441
-
=======
442
-
> We don't recommend adding debug values to every custom Hook. It's most valuable for custom Hooks that are part of shared libraries.
443
-
>>>>>>> 98c1d22fbef2638cafb03b07e0eabe2a6186fca8
444
407
445
408
#### Aplazar el formato de los valores de depuración
446
409
447
-
<<<<<<< HEAD
448
410
En algunos casos, formatear un valor para mostrar puede ser una operación costosa. También es innecesario a menos que un Hook sea realmente inspeccionado.
449
411
450
412
Por esta razón, `useDebugValue` acepta una función de formato como un segundo parámetro opcional. Esta función solo se llama si se inspeccionan los Hooks. Recibe el valor de depuración como parámetro y debe devolver un valor de visualización formateado.
451
413
452
414
Por ejemplo, un Hook personalizado que devolvió un valor de `Date` podría evitar llamar a la función `toDateString` innecesariamente al pasar el siguiente formateador:
453
-
=======
454
-
In some cases formatting a value for display might be an expensive operation. It's also unnecessary unless a Hook is actually inspected.
455
-
456
-
For this reason `useDebugValue` accepts a formatting function as an optional second parameter. This function is only called if the Hooks are inspected. It receives the debug value as a parameter and should return a formatted display value.
457
-
458
-
For example a custom Hook that returned a `Date` value could avoid calling the `toDateString` function unnecessarily by passing the following formatter:
0 commit comments