Skip to content

Commit e3fa2d6

Browse files
committed
part 6b
1 parent 4202ad4 commit e3fa2d6

File tree

2 files changed

+49
-46
lines changed

2 files changed

+49
-46
lines changed

src/content/6/en/part6b.md

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -514,13 +514,15 @@ const noteSlice = createSlice({
514514
// highlight-end
515515
```
516516
517-
The <em>createSlice</em> function's <em>name</em> parameter defines the prefix which is used in the action's type values. For example, the <em>createNote</em> action defined later will have the type value of <em>notes/createNote</em>. It is a good practice to give the parameter a value which is unique among the reducers. This way there won't be unexpected collisions between the application's action type values. The <em>initialState</em> parameter defines the reducer's initial state. The <em>reducers</em> parameter takes the reducer itself as an object, of which functions handle state changes caused by certain actions. Note that the <em>action.payload</em> in the function contains the argument provided by calling the action creator:
517+
The <em>createSlice</em> function's <em>name</em> parameter defines the prefix which is used in the action's type values. For example, the <em>createNote</em> action defined later will have the type value of <em>notes/createNote</em>. It is a good practice to give the parameter a value which is unique among the reducers. This way there won't be unexpected collisions between the application's action type values.
518+
The <em>initialState</em> parameter defines the reducer's initial state.
519+
The <em>reducers</em> parameter takes the reducer itself as an object, of which functions handle state changes caused by certain actions. Note that the <em>action.payload</em> in the function contains the argument provided by calling the action creator:
518520
519521
```js
520522
dispatch(createNote('Redux Toolkit is awesome!'))
521523
```
522524
523-
This dispatch call responds to dispatching the following object:
525+
This dispatch call is equivalent to dispatching the following object:
524526
525527
```js
526528
dispatch({ type: 'notes/createNote', payload: 'Redux Toolkit is awesome!' })
@@ -542,7 +544,7 @@ createNote(state, action) {
542544
543545
We are mutating <em>state</em> argument's array by calling the <em>push</em> method instead of returning a new instance of the array. What's this all about?
544546
545-
Redux Toolkit utilizes the [Immer](https://immerjs.github.io/immer/) library with reducers created by <em>createSlice</em> function, which makes it possible to mutate the <em>state</em> argument inside the reducer. Immer uses the mutated state to produce a new, immutable state and thus the state changes remain immutable. Note that <em>state</em> can be changed without "mutating" it, as we have done with the <em>toggleImportanceOf</em> action. In this case, the function <i>returns</i> the new state. Nevertheless mutating the state will often come in handy especially when a complex state needs to be updated.
547+
Redux Toolkit utilizes the [Immer](https://immerjs.github.io/immer/) library with reducers created by <em>createSlice</em> function, which makes it possible to mutate the <em>state</em> argument inside the reducer. Immer uses the mutated state to produce a new, immutable state and thus the state changes remain immutable. Note that <em>state</em> can be changed without "mutating" it, as we have done with the <em>toggleImportanceOf</em> action. In this case, the function directly <i>returns</i> the new state. Nevertheless mutating the state will often come in handy especially when a complex state needs to be updated.
546548
547549
The <em>createSlice</em> function returns an object containing the reducer as well as the action creators defined by the <em>reducers</em> parameter. The reducer can be accessed by the <em>noteSlice.reducer</em> property, whereas the action creators by the <em>noteSlice.actions</em> property. We can produce the file's exports in the following way:
548550
@@ -653,9 +655,9 @@ The following is printed to the console
653655
654656
![devtools console showing Handler,Target as null but IsRevoked as true](../../images/6/40new.png)
655657
656-
The output is interesting but not very useful. This is about the previously mentioned Immer library used by the Redux Toolkit, which is now used internally to save the state of the Store.
658+
The output is interesting but not very useful. This is about the previously mentioned Immer library used by the Redux Toolkit internally to save the state of the Store.
657659
658-
The status can be converted to a human-readable format, e.g. by converting it to a string and back to a JavaScript object as follows:
660+
The status can be converted to a human-readable format, e.g. by converting it first to a string and then back to a JavaScript object as follows:
659661
660662
```js
661663
console.log(JSON.parse(JSON.stringify(state))) // highlight-line
@@ -669,13 +671,13 @@ Console output is now human readable
669671
670672
[Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) is a Chrome addon that offers useful development tools for Redux. It can be used for example to inspect the Redux store's state and dispatch actions through the browser's console. When the store is created using Redux Toolkit's <em>configureStore</em> function, no additional configuration is needed for Redux DevTools to work.
671673
672-
Once the addon is installed, clicking the <i>Redux</i> tab in the browser's console should open the development tools:
674+
Once the addon is installed, clicking the <i>Redux</i> tab in the browser's developer tools, the Redux DevTools should open:
673675
674676
![browser with redux addon in devtools](../../images/6/42new.png)
675677
676678
You can inspect how dispatching a certain action changes the state by clicking the action:
677679
678-
![devtools inspecting notes tree in redux](../../images/6/43new.png)
680+
![devtools inspecting state tree in redux](../../images/6/43new.png)
679681
680682
It is also possible to dispatch actions to the store using the development tools:
681683
@@ -691,19 +693,19 @@ You can find the code for our current application in its entirety in the <i>part
691693
692694
Let's continue working on the anecdote application using Redux that we started in exercise 6.3.
693695
694-
#### 6.10 Better anecdotes, step8
696+
#### 6.10 Better Anecdotes, step 8
695697
696698
Install Redux Toolkit for the project. Move the Redux store creation into the file <i>store.js</i> and use Redux Toolkit's <em>configureStore</em> to create the store.
697699
698700
Change the definition of the <i>filter reducer and action creators</i> to use the Redux Toolkit's <em>createSlice</em> function.
699701
700702
Also, start using Redux DevTools to debug the application's state easier.
701703
702-
#### 6.11 Better anecdotes, step9
704+
#### 6.11 Better Anecdotes, step 9
703705
704706
Change also the definition of the <i>anecdote reducer and action creators</i> to use the Redux Toolkit's <em>createSlice</em> function.
705707
706-
#### 6.12 Better anecdotes, step10
708+
#### 6.12 Better Anecdotes, step 10
707709
708710
The application has a ready-made body for the <i>Notification</i> component:
709711
@@ -748,7 +750,7 @@ You will have to make changes to the application's existing reducer. Create a se
748750
749751
The application does not have to use the <i>Notification</i> component intelligently at this point in the exercises. It is enough for the application to display the initial value set for the message in the <i>notificationReducer</i>.
750752
751-
#### 6.13 Better anecdotes, step11
753+
#### 6.13 Better Anecdotes, step 11
752754
753755
Extend the application so that it uses the <i>Notification</i> component to display a message for five seconds when the user votes for an anecdote or creates a new anecdote:
754756

src/content/6/es/part6b.md

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -514,19 +514,21 @@ const noteSlice = createSlice({
514514
// highlight-end
515515
```
516516
517-
El parámetro <em>name</em> de la función <em>createSlice</em> define el prefijo que se utiliza en los valores de tipo de la acción. Por ejemplo, la acción <em>createNote</em> definida más adelante tendrá el valor de tipo <em>notes/createNote</em>. Es una buena práctica dar al parámetro un valor que sea único entre los reducers. De esta forma no habrá colisiones inesperadas entre los valores de tipo de acción de la aplicación. El parámetro <em>initialState</em> define el estado inicial del reducer. El parámetro <em>reducers</em> toma el propio reducer como un objeto, cuyas funciones manejan los cambios de estado causados por ciertas acciones. Tenga en cuenta que <em>action.payload</em> en la función contiene el argumento proporcionado al llamar al creador de la acción:
517+
El parámetro <em>name</em> de la función <em>createSlice</em> define el prefijo que se utiliza en los valores de tipo de la acción. Por ejemplo, la acción <em>createNote</em> definida más adelante tendrá el valor de tipo <em>notes/createNote</em>. Es una buena práctica dar al parámetro un valor que sea único entre los reducers. De esta forma no habrá colisiones inesperadas entre los valores de tipo de acción de la aplicación.
518+
El parámetro <em>initialState</em> define el estado inicial del reducer.
519+
El parámetro <em>reducers</em> toma al propio reducer como un objeto, cuyas funciones manejan los cambios de estado causados por ciertas acciones. Ten en cuenta que <em>action.payload</em> en la función contiene el argumento proporcionado al llamar al creador de la acción:
518520
519521
```js
520522
dispatch(createNote('Redux Toolkit is awesome!'))
521523
```
522524
523-
Esta llamada de <em>dispatch</em> responde al despacho del siguiente objeto:
525+
Esta llamada a dispatch equivale a enviar el siguiente objeto:
524526
525527
```js
526528
dispatch({ type: 'notes/createNote', payload: 'Redux Toolkit is awesome!' })
527529
```
528530
529-
Si has seguido todo de cerca, es posible que hayas notado que dentro de la acción <em>createNote</em>, parece suceder algo que viola el principio de inmutabilidad de los reducers mencionado anteriormente:
531+
Si has prestado atención, es posible que hayas notado que dentro de la acción <em>createNote</em>, parece suceder algo que viola el principio de inmutabilidad de los reducers mencionado anteriormente:
530532
531533
```js
532534
createNote(state, action) {
@@ -540,11 +542,11 @@ createNote(state, action) {
540542
}
541543
```
542544
543-
Estamos mutando el arreglo del parámetro <em>state</em> llamando al método <em>push</em> en lugar de devolver una nueva instancia del arreglo. ¿De qué se trata todo esto?
545+
Estamos mutando el array del argumento <em>state</em> al llamar al método <em>push</em> en lugar de devolver una nueva instancia del array. ¿De qué se trata todo esto?
544546
545-
Redux Toolkit utiliza la librería [Immer](https://immerjs.github.io/immer/) con reducers creados por la función <em>createSlice</em>, que hace posible mutar el parámetro del <em>estado</em> dentro del reducer. Immer usa el estado mutado para producir un nuevo estado inmutable y, por lo tanto, los cambios de estado permanecen inmutables. Tenga en cuenta que el <em>estado</em> se puede cambiar sin "mutarlo", como hemos hecho con la acción <em>toggleImportanceOf</em>. En este caso, la función <i>retorna</i> el nuevo estado. Sin embargo, mutar el estado a menudo será útil, especialmente cuando se necesita actualizar un estado complejo.
547+
Redux Toolkit utiliza la librería [Immer](https://immerjs.github.io/immer/) con reducers creados por la función <em>createSlice</em>, lo que hace posible mutar el argumento <em>state</em> dentro del reducer. Immer usa el estado mutado para producir un nuevo estado inmutable y, por lo tanto, los cambios de estado permanecen inmutables. Ten en cuenta que <em>state</em> se puede cambiar sin "mutarlo", como hemos hecho con la acción <em>toggleImportanceOf</em>. En este caso, la función <i>devuelve</i> el nuevo estado directamente. Sin embargo, mutar el estado a menudo será útil, especialmente cuando se necesita actualizar un estado complejo.
546548
547-
La función <em>createSlice</em> retorna un objeto que contiene el reducer así como los creadores de acciones definidos por el parámetro <em>reducers</em>. Se puede acceder al reducer mediante la propiedad <em>noteSlice.reducer</em>, mientras que a los creadores de acciones mediante la propiedad <em>noteSlice.actions</em>. Podemos producir las exportaciones del archivo de la siguiente manera:
549+
La función <em>createSlice</em> devuelve un objeto que contiene al reducer así como a los action creators definidos por el parámetro <em>reducers</em>. Se puede acceder al reducer mediante la propiedad <em>noteSlice.reducer</em>, mientras que a los action creators mediante la propiedad <em>noteSlice.actions</em>. Podemos producir las exportaciones del archivo de la siguiente manera:
548550
549551
```js
550552
const noteSlice = createSlice(/* ... */)
@@ -562,9 +564,9 @@ Las importaciones en otros archivos funcionarán igual que antes:
562564
import noteReducer, { createNote, toggleImportanceOf } from './reducers/noteReducer'
563565
```
564566
565-
Necesitamos modificar los nombres de los tipos de acción en las pruebas debido a las convenciones de ReduxToolkit:
567+
Necesitamos modificar los nombres de los tipos de las acciones en las pruebas debido a las convenciones de ReduxToolkit:
566568
567-
```js
569+
```js
568570
import noteReducer from './noteReducer'
569571
import deepFreeze from 'deep-freeze'
570572

@@ -617,11 +619,11 @@ describe('noteReducer', () => {
617619
})
618620
```
619621
620-
### Redux Toolkit and console.log
622+
### Redux Toolkit y console.log
621623
622624
Como hemos aprendido, console.log es una herramienta extremadamente poderosa, por lo general siempre nos salva de problemas.
623625
624-
Intentemos imprimir el estado de la store de Redux en la consola en medio del reductor creado con la función createSlice:
626+
Intentemos imprimir el estado del store de Redux en la consola en medio del reducer creado con la función createSlice:
625627
626628
```js
627629
const noteSlice = createSlice({
@@ -651,62 +653,61 @@ const noteSlice = createSlice({
651653
652654
Lo siguiente se imprime en la consola
653655
654-
![](../../images/6/40new.png)
656+
![consola mostrando Handler y Target como null pero isRevoked como true](../../images/6/40new.png)
655657
656-
La salida es interesante pero no muy útil. Esto trata de la librería Immer mencionada anteriormente utilizada por Redux Toolkit, que ahora se usa internamente para guardar el estado de la Tienda.
658+
Lo que vemos es interesante pero no muy útil. Esto tiene que ver con la librería Immer que mencionamos anteriormente y es utilizada por Redux Toolkit internamente para guardar el estado de la Tienda.
657659
658-
El estado se puede convertir a un formato legible por humanos, e.j. convirtiéndolo en una cadena y de nuevo en un objeto JavaScript de la siguiente manera:
660+
El estado se puede convertir a un formato legible por humanos, por ejemplo, convirtiéndolo primero en un string y luego de nuevo en un objeto JavaScript de la siguiente manera:
659661
660662
```js
661663
console.log(JSON.parse(JSON.stringify(state))) // highlight-line
662664
```
663665
664-
La salida de la consola ahora es legible para humanos
666+
Ahora lo que imprime la consola es legible para humanos
665667
666-
![](../../images/6/41new.png)
668+
![consola mostrando array de 2 notas](../../images/6/41new.png)
667669
668670
### Redux DevTools
669671
670672
[Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) es una extension de Chrome, que ofrece útiles herramientas de desarrollo para Redux. Se puede usar, por ejemplo, para inspeccionar el estado del store de Redux y enviar acciones (dispatch) a través de la consola del navegador. Cuando el store se crea usando la función <em>configureStore</em> de Redux Toolkit, no se necesita ninguna configuración adicional para que Redux DevTools funcione.
671673
672-
Una vez instalado el complemento, al hacer clic en la pestaña de Redux en la consola del navegador deberia abrir las herramientas de desarrollo:
674+
Una vez instalada la extension, al hacer clic en la pestaña de <i>Redux</i> en las herramientas de desarrollo del navegador, Redux DevTools debería abrirse:
673675
674-
![browser with redux addon in devtools](../../images/6/42new.png)
676+
![redux addon en herramientas de desarrollo](../../images/6/42new.png)
675677
676678
Puedes inspeccionar cómo el envío de una determinada acción cambia el estado haciendo clic en la acción:
677679
678-
![devtools inspecting notes tree in redux](../../images/6/43new.png)
680+
![devtools inspeccionando el árbol de state en redux](../../images/6/43new.png)
679681
680682
También es posible enviar acciones (dispatch) a la store utilizando las herramientas de desarrollo:
681683
682-
![devtools redux dispatching createNote with payload](../../images/6/44new.png)
684+
![devtools enviando createNote con payload](../../images/6/44new.png)
683685
684-
El código actual de la aplicación estan en la rama <i>part6-3</i> de [este repositorio de Github](https://github.com/fullstack-hy2020/redux-notes/tree/part6-3).
686+
El código actual de la aplicación se puede encontrar en [GitHub](https://github.com/fullstack-hy2020/redux-notes/tree/part6-3), en la rama <i>part6-3</i>.
685687
686688
</div>
687689
688690
<div class="tasks">
689691
690-
691692
### Ejercicios 6.10.-6.13.
692693
693694
Continuemos trabajando en la aplicación de anécdotas que comenzamos en el ejercicio 6.3, usando Redux Toolkit.
694695
695-
#### 6.10 Mejores anécdotas, paso 8
696+
#### 6.10 Mejores Anécdotas, paso 8
696697
697-
Instale Redux Toolkit en el proyecto. Mueva la creación de la store de redux a su propio archivo <i>store.js</i> y use la función <em>configureStore</em> para crear la store.
698+
Instala Redux Toolkit en el proyecto. Mueve la creación del store de Redux a su propio archivo <i>store.js</i> y utiliza la función <em>configureStore</em> para crear el store.
698699
699-
Cambie la definición del <i>Filter reducer y creación de acciones</i> para usar la función <em>createSlice</em> de Redux Toolkit.
700+
Cambia la definición del <i>filter reducer y sus action creators</i> para usar la función <em>createSlice</em> de Redux Toolkit.
700701
701-
También, empiece a usar los Redux DevTools para depurar el estado de la aplicación fácilmente.
702+
También, comienza a utilizar Redux DevTools para depurar el estado de la aplicación fácilmente.
702703
703-
#### 6.11 Mejores anécdotas, paso 9
704+
#### 6.11 Mejores Anécdotas, paso 9
704705
705-
Cambie también la definición de <i>Anecdote reducer y creación de acciones</i> para usar la función <em>createSlice</em> de Redux Toolkit.
706+
Cambia también la definición de <i>anecdote reducer y sus action creators</i> para usar la función <em>createSlice</em> de Redux Toolkit.
706707
707-
#### 6.12 Mejores anécdotas, paso 10
708+
#### 6.12 Mejores Anécdotas, paso 10
708709
709-
La aplicación tiene un cuerpo listo para usar el componente <i>Notification</i>:
710+
La aplicación tiene el esqueleto del componente <i>Notification</i> listo para utilizarlo:
710711
711712
```js
712713
const Notification = () => {
@@ -725,7 +726,7 @@ const Notification = () => {
725726
export default Notification
726727
```
727728
728-
Extienda el componente para que muestre el mensaje almacenado en el store de redux, haciendo que el componente tome la siguiente forma:
729+
Extiende el componente para que muestre el mensaje almacenado en el store de redux, haciendo que el componente tome la siguiente forma:
729730
730731
```js
731732
import { useSelector } from 'react-redux' // highlight-line
@@ -745,16 +746,16 @@ const Notification = () => {
745746
}
746747
```
747748
748-
Tendrá que realizar cambios en el reducer existente de la aplicación. Cree un reducer separado para la nueva funcionalidad usando la función <em>createSlice</em> de Redux Toolkit.
749+
Tendrás que realizar cambios en el reducer existente de la aplicación. Crea un reducer separado para la nueva funcionalidad usando la función <em>createSlice</em> de Redux Toolkit.
749750
750751
La aplicación no tiene que utilizar el componente <i>Notification</i> completamente en este punto de los ejercicios. Es suficiente con que la aplicación muestre el valor inicial establecido para el mensaje en el <i>notificationReducer</i>.
751752
752-
#### 6.13 Mejores anécdotas, paso 11
753+
#### 6.13 Mejores Anécdotas, paso 11
753754
754-
Extienda la aplicación para que utilice el componente <i>Notification</i> para mostrar un mensaje durante cinco segundos cuando el usuario vote por una anécdota o cree una nueva anécdota:
755+
Extiende la aplicación para que utilice el componente <i>Notification</i> para mostrar un mensaje durante cinco segundos cuando el usuario vote por una anécdota o cree una nueva anécdota:
755756
756-
![browser showing message of having voted](../../images/6/8ea.png)
757+
![navegador mostrando el mensaje de haber votado](../../images/6/8ea.png)
757758
758-
Se recomienda crear [creadores de acciones](https://redux-toolkit.js.org/api/createSlice#reducers) independientes para configurar y eliminar notificaciones.
759+
Se recomienda crear [action creators](https://redux-toolkit.js.org/api/createSlice#reducers) independientes para configurar y eliminar notificaciones.
759760
760761
</div>

0 commit comments

Comments
 (0)