chore(i18n,curriculum): processed translations (#42669)
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036162
|
||||
title: Create a Stateless Functional Component
|
||||
title: Crear un componente funcional sin estado
|
||||
challengeType: 6
|
||||
forumTopicId: 301392
|
||||
dashedName: create-a-stateless-functional-component
|
||||
@ -8,14 +8,13 @@ dashedName: create-a-stateless-functional-component
|
||||
|
||||
# --description--
|
||||
|
||||
Components are the core of React. Everything in React is a component and here you will learn how to create one.
|
||||
Los componentes son el núcleo de React. Todo en React es un componente y aquí aprenderás a crear uno.
|
||||
|
||||
There are two ways to create a React component. The first way is to use a JavaScript function. Defining a component in this way creates a *stateless functional component*. The concept of state in an application will be covered in later challenges. For now, think of a stateless component as one that can receive data and render it, but does not manage or track changes to that data. (We'll cover the second way to create a React component in the next challenge.)
|
||||
Hay dos maneras de crear un componente React. La primera forma es utilizar una función JavaScript. Definir un componente de esta manera crea un *componente funcional sin estado*. El concepto de estado en una solicitud se abordará en retos posteriores. Por ahora, piensa en un componente sin estado como uno que puede recibir datos y renderizarlos, pero no administra o rastrea los cambios en esos datos. (Cubriremos la segunda manera de crear un componente React en el siguiente desafío.)
|
||||
|
||||
To create a component with a function, you simply write a JavaScript function that returns either JSX or `null`. One important thing to note is that React requires your function name to begin with a capital letter. Here's an example of a stateless functional component that assigns an HTML class in JSX:
|
||||
Para crear un componente con una función, simplemente escribe una función JavaScript que devuelva ya sea JSX o `null`. Una cosa importante a tener en cuenta es que React requiere que tu nombre de función comience con una letra mayúscula. Aquí hay un ejemplo de un componente funcional sin estado que asigna una clase HTML en JSX:
|
||||
|
||||
```jsx
|
||||
// After being transpiled, the <div> will have a CSS class of 'customClass'
|
||||
const DemoComponent = function() {
|
||||
return (
|
||||
<div className='customClass' />
|
||||
@ -23,17 +22,19 @@ const DemoComponent = function() {
|
||||
};
|
||||
```
|
||||
|
||||
Because a JSX component represents HTML, you could put several components together to create a more complex HTML page. This is one of the key advantages of the component architecture React provides. It allows you to compose your UI from many separate, isolated components. This makes it easier to build and maintain complex user interfaces.
|
||||
Después de ser transpilado, el `<div>` tendrá una clase CSS de `customClass`.
|
||||
|
||||
Debido a que un componente JSX representa HTML, podrías poner varios componentes juntos para crear una página HTML más compleja. Esta es una de las ventajas clave de la arquitectura de componentes que React proporciona. Te permite componer tu interfaz de usuario de muchos componentes separados y aislados. Esto hace más fácil construir y mantener complejas interfaces de usuario.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has a function called `MyComponent`. Complete this function so it returns a single `div` element which contains some string of text.
|
||||
El editor de código tiene una función llamada `MyComponent`. Completa esta función para que retorne un único elemento `div` que contiene alguna cadena de texto.
|
||||
|
||||
**Note:** The text is considered a child of the `div` element, so you will not be able to use a self-closing tag.
|
||||
**Nota:** El texto se considera hijo del elemento `div`, por lo que no podrás utilizar una etiqueta de autocierre.
|
||||
|
||||
# --hints--
|
||||
|
||||
`MyComponent` should return JSX.
|
||||
`MyComponent` debe retornar JSX.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -44,7 +45,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`MyComponent` should return a `div` element.
|
||||
`MyComponent` debe renderizar un elemento `div`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -55,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `div` element should contain a string of text.
|
||||
El elemento `div` debe contener una cadena de texto.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036147
|
||||
title: Connect Redux to React
|
||||
title: Connettere Redux a React
|
||||
challengeType: 6
|
||||
forumTopicId: 301426
|
||||
dashedName: connect-redux-to-react
|
||||
@ -8,23 +8,23 @@ dashedName: connect-redux-to-react
|
||||
|
||||
# --description--
|
||||
|
||||
Now that you've written both the `mapStateToProps()` and the `mapDispatchToProps()` functions, you can use them to map `state` and `dispatch` to the `props` of one of your React components. The `connect` method from React Redux can handle this task. This method takes two optional arguments, `mapStateToProps()` and `mapDispatchToProps()`. They are optional because you may have a component that only needs access to `state` but doesn't need to dispatch any actions, or vice versa.
|
||||
Ora che hai scritto sia la funzione `mapStateToProps()` che la funzione `mapDispatchToProps()`, puoi utilizzarle per mappare lo `state` e spedirlo (`dispatch`) alle `props` di uno dei tuoi componenti React. Il metodo `connect` può gestire questa attività per passare i dati da React a Redux. Questo metodo richiede due argomenti opzionali, `mapStateToProps()` e `mapDispatchToProps()`. Sono opzionali perché potresti avere un componente che ha bisogno solo di accedere allo `state` ma non ha bisogno di inviare alcuna azione, o viceversa.
|
||||
|
||||
To use this method, pass in the functions as arguments, and immediately call the result with your component. This syntax is a little unusual and looks like:
|
||||
Per usare questo metodo, passa le funzioni come argomenti, e chiama immediatamente il risultato con il tuo componente. Questa sintassi è un po' insolita e appare così:
|
||||
|
||||
```js
|
||||
connect(mapStateToProps, mapDispatchToProps)(MyComponent)
|
||||
```
|
||||
|
||||
**Note:** If you want to omit one of the arguments to the `connect` method, you pass `null` in its place.
|
||||
**Nota:** Se vuoi omettere uno degli argomenti del metodo `connect`, passa `null` al loro posto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has the `mapStateToProps()` and `mapDispatchToProps()` functions and a new React component called `Presentational`. Connect this component to Redux with the `connect` method from the `ReactRedux` global object, and call it immediately on the `Presentational` component. Assign the result to a new `const` called `ConnectedComponent` that represents the connected component. That's it, now you're connected to Redux! Try changing either of `connect`'s arguments to `null` and observe the test results.
|
||||
L'editor di codice contiene le funzioni `mapStateToProps()` e `mapDispatchToProps()` e un nuovo componente React chiamato `Presentational`. Collega questo componente a Redux con il metodo `connect` dall'oggetto globale `ReactRedux`, e chiamalo immediatamente sul componente `Presentational`. Assegna il risultato a una nuova `const` chiamata `ConnectedComponent` che rappresenta il componente collegato. Questo è tutto, ora sei connesso a Redux! Prova a impostare uno dei due argomenti di `connect` a `null` e osserva i risultati del test.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `Presentational` component should render.
|
||||
Il componente `Presentational` dovrebbe effettuare il render.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive a prop `messages` via `connect`.
|
||||
Il componente `Presentational` dovrebbe ricevere una prop `messages` via `connect`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive a prop `submitNewMessage` via `connect`.
|
||||
Il componente `Presentational` dovrebbe ricevere una prop `submitNewMessage` via `connect`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036148
|
||||
title: Connect Redux to the Messages App
|
||||
title: Connettere Redux all'app Messaggi
|
||||
challengeType: 6
|
||||
forumTopicId: 301427
|
||||
dashedName: connect-redux-to-the-messages-app
|
||||
@ -8,17 +8,17 @@ dashedName: connect-redux-to-the-messages-app
|
||||
|
||||
# --description--
|
||||
|
||||
Now that you understand how to use `connect` to connect React to Redux, you can apply what you've learned to your React component that handles messages.
|
||||
Ora che sai come usare `connect` per connettere React a Redux, puoi applicare quello che hai imparato al tuo componente React che gestisce i messaggi.
|
||||
|
||||
In the last lesson, the component you connected to Redux was named `Presentational`, and this wasn't arbitrary. This term *generally* refers to React components that are not directly connected to Redux. They are simply responsible for the presentation of UI and do this as a function of the props they receive. By contrast, container components are connected to Redux. These are typically responsible for dispatching actions to the store and often pass store state to child components as props.
|
||||
Nell'ultima lezione, il componente che hai collegato a Redux è stato chiamato `Presentational`, e questo non è stato arbitrario. Questo termine *generalmente* si riferisce a componenti React che non sono direttamente collegati a Redux. Sono semplicemente responsabili della presentazione dell'interfaccia utente e fanno questo in funzione delle props che ricevono. Al contrario, i componenti contenitore sono collegati a Redux. Essi sono tipicamente responsabili della spedizione delle azioni allo store e spesso passano lo stato dello store ai componenti figli come props.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has all the code you've written in this section so far. The only change is that the React component is renamed to `Presentational`. Create a new component held in a constant called `Container` that uses `connect` to connect the `Presentational` component to Redux. Then, in the `AppWrapper`, render the React Redux `Provider` component. Pass `Provider` the Redux `store` as a prop and render `Container` as a child. Once everything is setup, you will see the messages app rendered to the page again.
|
||||
L'editor di codice contiene tutto il codice che hai scritto finora in questa sezione. L'unico cambiamento è che il componente React è stato rinominato in `Presentational`. Crea un nuovo componente memorizzato in una costante chiamata `Container` che utilizza `connect` per collegare il componente `Presentational` a Redux. Poi, in `AppWrapper`, presenta il componente React Redux `Provider`. Passa a `Provider` lo `store` di Redux come una prop e presenta `Container` come figlio. Una volta che sarà tutto configurato, vedrai nuovamente l'app dei messaggi presentata nella pagina.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `AppWrapper` should render to the page.
|
||||
L' `AppWrapper` dovrebbe essere presentata nella pagina.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -29,7 +29,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should render to page.
|
||||
Il componente `Presentational` dovrebbe essere presentato nella pagina.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should render an `h2`, `input`, `button`, and `ul` elements.
|
||||
Il componente `Presentational` dovrebbe fare il render degli elementi `h2`, `input`, `button`e `ul`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive `messages` from the Redux store as a prop.
|
||||
Il componente `Presentational` dovrebbe ricevere `messages` dallo store Redux come prop.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -70,7 +70,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive the `submitMessage` action creator as a prop.
|
||||
Il componente `Presentational` dovrebbe ricevere il creatore dell'azione `submitMessage` come prop.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036149
|
||||
title: Extract Local State into Redux
|
||||
title: Estrai lo stato locale in Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301428
|
||||
dashedName: extract-local-state-into-redux
|
||||
@ -8,17 +8,17 @@ dashedName: extract-local-state-into-redux
|
||||
|
||||
# --description--
|
||||
|
||||
You're almost done! Recall that you wrote all the Redux code so that Redux could control the state management of your React messages app. Now that Redux is connected, you need to extract the state management out of the `Presentational` component and into Redux. Currently, you have Redux connected, but you are handling the state locally within the `Presentational` component.
|
||||
Hai quasi finito! Ricorda che hai scritto tutto il codice Redux in modo che Redux possa controllare la gestione dello stato della tua app di messaggi React. Ora che Redux è connesso, è necessario estrarre la gestione dello stato dal componente `Presentational` per metterla in Redux. Attualmente, hai collegato Redux, ma stai gestendo lo stato localmente all'interno del componente `Presentational`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the `Presentational` component, first, remove the `messages` property in the local `state`. These messages will be managed by Redux. Next, modify the `submitMessage()` method so that it dispatches `submitNewMessage()` from `this.props`, and pass in the current message input from local `state` as an argument. Because you removed `messages` from local state, remove the `messages` property from the call to `this.setState()` here as well. Finally, modify the `render()` method so that it maps over the messages received from `props` rather than `state`.
|
||||
Nel componente `Presentational`, per prima cosa, rimuovi la proprietà `messages` nello `state` locale. Questi messaggi saranno gestiti da Redux. Successivamente, modifica il metodo `submitMessage()` in modo che invii `submitNewMessage()` da `this.props`, e gli passi l'input del messaggio corrente prendendolo dallo `state` locale come argomento. Poiché hai rimosso `messages` dallo stato locale, rimuovi la proprietà `messages` dalla chiamata a `this.setState()` anche qui. Infine, modifica il metodo `render()` in modo che mappi i messaggi ricevuti da `props` piuttosto che dallo `state`.
|
||||
|
||||
Once these changes are made, the app will continue to function the same, except Redux manages the state. This example also illustrates how a component may have local `state`: your component still tracks user input locally in its own `state`. You can see how Redux provides a useful state management framework on top of React. You achieved the same result using only React's local state at first, and this is usually possible with simple apps. However, as your apps become larger and more complex, so does your state management, and this is the problem Redux solves.
|
||||
Una volta che queste modifiche saranno state fatte, l'applicazione continuerà a funzionare ugualmente, solo che sarà Redux a gestire lo stato. Questo esempio illustra anche come un componente può avere uno `state` locale: il tuo componente traccia ancora l'input dell'utente localmente nel proprio `state`. Puoi vedere come Redux fornisce un utile framework di gestione dello stato basato su React. Hai raggiunto inizialmente lo stesso risultato usando solo lo stato locale di React, e questo è di solito possibile con applicazioni semplici. Tuttavia, mano a mano che le applicazioni diventeranno più grandi e più complesse, lo stesso farà lo stato, e questo è il problema risolto da Redux.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `AppWrapper` should render to the page.
|
||||
L' `AppWrapper` dovrebbe essere presentata nella pagina.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -29,7 +29,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should render to page.
|
||||
Il componente `Presentational` dovrebbe essere presentato nella pagina.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should render an `h2`, `input`, `button`, and `ul` elements.
|
||||
Il componente `Presentational` dovrebbe fare il render degli elementi `h2`, `input`, `button`e `ul`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive `messages` from the Redux store as a prop.
|
||||
Il componente `Presentational` dovrebbe ricevere `messages` dallo store Redux come prop.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -70,7 +70,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Presentational` component should receive the `submitMessage` action creator as a prop.
|
||||
Il componente `Presentational` dovrebbe ricevere il creatore dell'azione `submitMessage` come prop.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -83,7 +83,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The state of the `Presentational` component should contain one property, `input`, which is initialized to an empty string.
|
||||
Lo stato del componente `Presentational` dovrebbe contenere una proprietà, `input`, che è inizializzata a una stringa vuota.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -100,7 +100,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Typing in the `input` element should update the state of the `Presentational` component.
|
||||
Digitando nell'elemento `input` si dovrebbe aggiornare lo stato del componente `Presentational`.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -124,7 +124,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
Dispatching the `submitMessage` on the `Presentational` component should update Redux store and clear the input in local state.
|
||||
La spedizione del `submitMessage` nel componente `Presentational` dovrebbe aggiornare lo store di Redux e cancellare l'input nello stato locale.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -156,7 +156,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
The `Presentational` component should render the `messages` from the Redux store.
|
||||
Il componente `Presentational` dovrebbe presentare i `messages` dallo store di Redux.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036143
|
||||
title: Extract State Logic to Redux
|
||||
title: Estrarre la logica dello stato in Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301429
|
||||
dashedName: extract-state-logic-to-redux
|
||||
@ -8,23 +8,23 @@ dashedName: extract-state-logic-to-redux
|
||||
|
||||
# --description--
|
||||
|
||||
Now that you finished the React component, you need to move the logic it's performing locally in its `state` into Redux. This is the first step to connect the simple React app to Redux. The only functionality your app has is to add new messages from the user to an unordered list. The example is simple in order to demonstrate how React and Redux work together.
|
||||
Ora che hai finito il componente React, devi spostare la logica che esegue localmente nel suo `state` in Redux. Questo è il primo passo per collegare la semplice applicazione React a Redux. L'unica funzionalità che la tua app ha è di aggiungere nuovi messaggi dall'utente a un elenco puntato. L'esempio è semplice e serve a dimostrare come React e Redux lavorano insieme.
|
||||
|
||||
# --instructions--
|
||||
|
||||
First, define an action type `ADD` and set it to a const `ADD`. Next, define an action creator `addMessage()` which creates the action to add a message. You'll need to pass a `message` to this action creator and include the message in the returned `action`.
|
||||
In primo luogo, definisci un tipo di azione `ADD` e impostalo a una const `ADD`. Quindi, definisci un creatore di azioni `addMessage()` che crea l'azione per aggiungere un messaggio. Dovrai passare un `message` a questo creatore di azioni e includere il messaggio nell'`action` restituita.
|
||||
|
||||
Then create a reducer called `messageReducer()` that handles the state for the messages. The initial state should equal an empty array. This reducer should add a message to the array of messages held in state, or return the current state. Finally, create your Redux store and pass it the reducer.
|
||||
Quindi crea un reducer chiamato `messageReducer()` che gestisca lo stato dei messaggi. Lo stato iniziale dovrebbe essere un array vuoto. Questo reducer dovrebbe aggiungere un messaggio all'array di messaggi tenuti nello stato o restituire lo stato attuale. Infine, crea il tuo store di Redux e passagli il reducer.
|
||||
|
||||
# --hints--
|
||||
|
||||
The const `ADD` should exist and hold a value equal to the string `ADD`
|
||||
La costante `ADD` dovrebbe esistere e contenere un valore uguale alla stringa `ADD`
|
||||
|
||||
```js
|
||||
assert(ADD === 'ADD');
|
||||
```
|
||||
|
||||
The action creator `addMessage` should return an object with `type` equal to `ADD` and `message` equal to the message that is passed in.
|
||||
Il creatore di azioni `addMessage` dovrebbe restituire un oggetto con `type` uguale a `ADD` e `message` uguale al messaggio che gli viene passato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,13 +35,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`messageReducer` should be a function.
|
||||
`messageReducer` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof messageReducer === 'function');
|
||||
```
|
||||
|
||||
The store should exist and have an initial state set to an empty array.
|
||||
Lo store dovrebbe esistere e avere uno stato iniziale impostato su un array vuoto.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -52,7 +52,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching `addMessage` against the store should immutably add a new message to the array of messages held in state.
|
||||
Inviare `addMessage` allo store dovrebbe sempre aggiungere un nuovo messaggio all'array di messaggi tenuti nello stato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `messageReducer` should return the current state if called with any other actions.
|
||||
Il `messageReducer` dovrebbe restituire lo stato corrente se chiamato con altre azioni.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036141
|
||||
title: Getting Started with React Redux
|
||||
title: Iniziare con React Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301430
|
||||
dashedName: getting-started-with-react-redux
|
||||
@ -8,19 +8,19 @@ dashedName: getting-started-with-react-redux
|
||||
|
||||
# --description--
|
||||
|
||||
This series of challenges introduces how to use Redux with React. First, here's a review of some of the key principles of each technology. React is a view library that you provide with data, then it renders the view in an efficient, predictable way. Redux is a state management framework that you can use to simplify the management of your application's state. Typically, in a React Redux app, you create a single Redux store that manages the state of your entire app. Your React components subscribe to only the pieces of data in the store that are relevant to their role. Then, you dispatch actions directly from React components, which then trigger store updates.
|
||||
Questa serie di sfide mostra come utilizzare Redux con React. In primo luogo, ecco un ripasso di alcuni dei principi fondamentali di ciascuna tecnologia. React è una libreria di visualizzazione alla quale fornisci dei dati, che poi li presenta in modo efficiente e affidabile. Redux è un framework di gestione dello stato che puoi usare per semplificare la gestione dello stato della tua applicazione. In genere, in un'applicazione React Redux, si crea un singolo store Redux che gestisce lo stato dell'intera app. I componenti React ricevono solo i dati presenti nello store che sono rilevanti per il loro ruolo. Quindi si inviano le azioni direttamente dai componenti React, che quindi attivano gli aggiornamenti dello store.
|
||||
|
||||
Although React components can manage their own state locally, when you have a complex app, it's generally better to keep the app state in a single location with Redux. There are exceptions when individual components may have local state specific only to them. Finally, because Redux is not designed to work with React out of the box, you need to use the `react-redux` package. It provides a way for you to pass Redux `state` and `dispatch` to your React components as `props`.
|
||||
Anche se i componenti React possono gestire il proprio stato localmente, quando si dispone di un'app complessa è generalmente meglio mantenere lo stato dell'app in una singola posizione con Redux. Ci sono eccezioni quando i singoli componenti possono avere uno stato locale specifico solo per essi. Infine, dato che Redux non è progettato per essere pronto all'uso con React, è necessario utilizzare il pacchetto `react-redux`. Esso ti fornisce un modo per passare lo `state` di Redux e spedirlo (`dispatch`) ai componenti React sotto forma di `props`.
|
||||
|
||||
Over the next few challenges, first, you'll create a simple React component which allows you to input new text messages. These are added to an array that's displayed in the view. This should be a nice review of what you learned in the React lessons. Next, you'll create a Redux store and actions that manage the state of the messages array. Finally, you'll use `react-redux` to connect the Redux store with your component, thereby extracting the local state into the Redux store.
|
||||
Nel corso delle prossime sfide, in primo luogo, creerai un semplice componente React che ti permetterà di inserire nuovi messaggi di testo. Questi vengono aggiunti ad un array che viene visualizzato nella vista. Questo dovrebbe essere un bel ripasso di quello che hai imparato nelle lezioni di React. Successivamente, creerai uno store Redux e delle azioni che gestiranno lo stato dell'array dei messaggi. Infine, userai `react-redux` per collegare lo store Redux con il tuo componente, estraendo lo stato locale nello store di Redux.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Start with a `DisplayMessages` component. Add a constructor to this component and initialize it with a state that has two properties: `input`, that's set to an empty string, and `messages`, that's set to an empty array.
|
||||
Inizia con un componente `DisplayMessages`. Aggiungi un costruttore a questo componente e inizializzalo con uno stato che abbia due proprietà: `input`, impostato su una stringa vuota e `messages`, impostato su un array vuoto.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `DisplayMessages` component should render an empty `div` element.
|
||||
Il componente `DisplayMessages` dovrebbe presentare un elemento `div` vuoto.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `DisplayMessages` constructor should be called properly with `super`, passing in `props`.
|
||||
Il costruttore `DisplayMessages` dovrebbe essere chiamato correttamente con `super`, passandogli le `props`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -46,7 +46,7 @@ The `DisplayMessages` constructor should be called properly with `super`, passin
|
||||
);
|
||||
```
|
||||
|
||||
The `DisplayMessages` component should have an initial state equal to `{input: "", messages: []}`.
|
||||
Il componente `DisplayMessages` dovrebbe avere uno stato iniziale uguale a `{input: "", messages: []}`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036142
|
||||
title: Manage State Locally First
|
||||
title: Gestire prima lo stato locale
|
||||
challengeType: 6
|
||||
forumTopicId: 301431
|
||||
dashedName: manage-state-locally-first
|
||||
@ -8,19 +8,19 @@ dashedName: manage-state-locally-first
|
||||
|
||||
# --description--
|
||||
|
||||
Here you'll finish creating the `DisplayMessages` component.
|
||||
Qui finirai di creare il componente `DisplayMessages`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
First, in the `render()` method, have the component render an `input` element, `button` element, and `ul` element. When the `input` element changes, it should trigger a `handleChange()` method. Also, the `input` element should render the value of `input` that's in the component's state. The `button` element should trigger a `submitMessage()` method when it's clicked.
|
||||
In primo luogo, nel metodo `render()`, fai in modo che sia presentato un elemento `input`, un `button` e un `ul`. Quando l'elemento `input` cambia, dovrebbe attivare un metodo `handleChange()`. Inoltre, l'elemento `input` dovrebbe presentare il valore di `input` che è nello stato del componente. L'elemento `button` dovrebbe attivare un metodo `submitMessage()` quando viene cliccato.
|
||||
|
||||
Second, write these two methods. The `handleChange()` method should update the `input` with what the user is typing. The `submitMessage()` method should concatenate the current message (stored in `input`) to the `messages` array in local state, and clear the value of the `input`.
|
||||
In secondo luogo, scrivi questi due metodi. Il metodo `handleChange()` dovrebbe aggiornare l'`input` con quello che l'utente sta digitando. Il metodo `submitMessage()` dovrebbe concatenare il messaggio corrente (memorizzato in `input`) all'array `messages` nello stato locale, e cancellare il valore dell'`input`.
|
||||
|
||||
Finally, use the `ul` to map over the array of `messages` and render it to the screen as a list of `li` elements.
|
||||
Infine, usa `ul` per mappare l'array `messages` e presentarlo sullo schermo come un elenco di elementi `li`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `DisplayMessages` component should initialize with a state equal to `{ input: "", messages: [] }`.
|
||||
Il componente `DisplayMessages` dovrebbe inizializzare con uno stato uguale a `{ input: "", messages: [] }`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -36,7 +36,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `DisplayMessages` component should render a `div` containing an `h2` element, a `button` element, a `ul` element, and `li` elements as children.
|
||||
Il componente `DisplayMessages` dovrebbe rendere un `div` contenente un elemento `h2`, un elemento `button`, un elemento `ul`, e degli elementi `li` come figli.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -58,13 +58,13 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
`.map` should be used on the `messages` array.
|
||||
`.map` dovrebbe essere utilizzato nell'array `messages`.
|
||||
|
||||
```js
|
||||
assert(code.match(/this\.state\.messages\.map/g));
|
||||
```
|
||||
|
||||
The `input` element should render the value of `input` in local state.
|
||||
L'elemento `input` dovrebbe presentare il valore di `input` nello stato locale.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -83,7 +83,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
Calling the method `handleChange` should update the `input` value in state to the current input.
|
||||
Chiamare il metodo `handleChange` dovrebbe aggiornare il valore `input` nello stato in base all'input corrente.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -106,7 +106,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
Clicking the `Add message` button should call the method `submitMessage` which should add the current `input` to the `messages` array in state.
|
||||
Fare clic sul pulsante `Add message` dovrebbe chiamare il metodo `submitMessage` che dovrebbe aggiungere l'`input` corrente all'array `messages` nello stato.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@ -149,7 +149,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
The `submitMessage` method should clear the current input.
|
||||
Il metodo `submitMessage` dovrebbe cancellare l'input corrente.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036146
|
||||
title: Map Dispatch to Props
|
||||
title: Mappare la spedizione delle props
|
||||
challengeType: 6
|
||||
forumTopicId: 301432
|
||||
dashedName: map-dispatch-to-props
|
||||
@ -8,9 +8,9 @@ dashedName: map-dispatch-to-props
|
||||
|
||||
# --description--
|
||||
|
||||
The `mapDispatchToProps()` function is used to provide specific action creators to your React components so they can dispatch actions against the Redux store. It's similar in structure to the `mapStateToProps()` function you wrote in the last challenge. It returns an object that maps dispatch actions to property names, which become component `props`. However, instead of returning a piece of `state`, each property returns a function that calls `dispatch` with an action creator and any relevant action data. You have access to this `dispatch` because it's passed in to `mapDispatchToProps()` as a parameter when you define the function, just like you passed `state` to `mapStateToProps()`. Behind the scenes, React Redux is using Redux's `store.dispatch()` to conduct these dispatches with `mapDispatchToProps()`. This is similar to how it uses `store.subscribe()` for components that are mapped to `state`.
|
||||
La funzione `mapDispatchToProps()` viene utilizzata per fornire specifici creatori di azioni ai componenti React in modo che possano inviare azioni allo store di Redux. La struttura è simile alla funzione `mapStateToProps()` che hai scritto nell'ultima sfida. Essa restituisce un oggetto che mappa azioni di invio a nomi di proprietà, che diventano `props` del componente. Tuttavia, invece di restituire una parte dello `state`, ogni proprietà restituisce una funzione che chiama `dispatch` con un creatore di azione e tutti i dati rilevanti per l'azione. Hai accesso a questa `dispatch` perché è passata a `mapDispatchToProps()` come parametro quando definisci la funzione, proprio come hai passato `state` a `mapStateToProps()`. Dietro le quinte, React Redux sta usando `store.dispatch()` di Redux per eseguire queste spedizioni con `mapDispatchToProps()`. Questo è simile a come usa `store.subscribe()` per i componenti che sono mappati allo `state`.
|
||||
|
||||
For example, you have a `loginUser()` action creator that takes a `username` as an action payload. The object returned from `mapDispatchToProps()` for this action creator would look something like:
|
||||
Ad esempio, hai un creatore di azione `loginUser()` che richiede uno `username` come payload dell'azione. L'oggetto restituito da `mapDispatchToProps()` per questo creatore di azione sarà di questo tipo:
|
||||
|
||||
```jsx
|
||||
{
|
||||
@ -22,11 +22,11 @@ For example, you have a `loginUser()` action creator that takes a `username` as
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor provides an action creator called `addMessage()`. Write the function `mapDispatchToProps()` that takes `dispatch` as an argument, then returns an object. The object should have a property `submitNewMessage` set to the dispatch function, which takes a parameter for the new message to add when it dispatches `addMessage()`.
|
||||
L'editor di codice fornisce un creatore di azioni chiamato `addMessage()`. Scrivi la funzione `mapDispatchToProps()` che richiede `dispatch` come argomento, quindi restituisce un oggetto. L'oggetto dovrebbe avere una proprietà `submitNewMessage` impostata alla funzione dispatch, che prende un parametro per il nuovo messaggio quando effettua il dispatch di `addMessage()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`addMessage` should return an object with keys `type` and `message`.
|
||||
`addMessage` dovrebbe restituire un oggetto con chiavi `type` e `message`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,19 +40,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`mapDispatchToProps` should be a function.
|
||||
`mapDispatchToProps` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof mapDispatchToProps === 'function');
|
||||
```
|
||||
|
||||
`mapDispatchToProps` should return an object.
|
||||
`mapDispatchToProps` dovrebbe restituire un oggetto.
|
||||
|
||||
```js
|
||||
assert(typeof mapDispatchToProps() === 'object');
|
||||
```
|
||||
|
||||
Dispatching `addMessage` with `submitNewMessage` from `mapDispatchToProps` should return a message to the dispatch function.
|
||||
Spedire `addMessage` con `submitNewMessage` da `mapDispatchToProps` dovrebbe restituire un messaggio alla funzione dispatch.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036145
|
||||
title: Map State to Props
|
||||
title: Mappare lo stato sulle props
|
||||
challengeType: 6
|
||||
forumTopicId: 301433
|
||||
dashedName: map-state-to-props
|
||||
@ -8,37 +8,37 @@ dashedName: map-state-to-props
|
||||
|
||||
# --description--
|
||||
|
||||
The `Provider` component allows you to provide `state` and `dispatch` to your React components, but you must specify exactly what state and actions you want. This way, you make sure that each component only has access to the state it needs. You accomplish this by creating two functions: `mapStateToProps()` and `mapDispatchToProps()`.
|
||||
Il componente `Provider` consente di fornire `state` e `dispatch` ai componenti React, ma devi specificare esattamente quale stato e azioni desideri. In questo modo, ti assicuri che ogni componente abbia accesso solo allo stato di cui ha bisogno. Lo si ottiene creando due funzioni: `mapStateToProps()` e `mapDispatchToProps()`.
|
||||
|
||||
In these functions, you declare what pieces of state you want to have access to and which action creators you need to be able to dispatch. Once these functions are in place, you'll see how to use the React Redux `connect` method to connect them to your components in another challenge.
|
||||
In queste funzioni, dichiari a quali parti dello stato vuoi avere accesso e quali creatori di azione devi essere in grado di inviare. Una volta che queste funzioni saranno pronte, vedrai come utilizzare il metodo React Redux `connect` per collegarli ai tuoi componenti in un'altra sfida.
|
||||
|
||||
**Note:** Behind the scenes, React Redux uses the `store.subscribe()` method to implement `mapStateToProps()`.
|
||||
**Nota:** Dietro le quinte, React Redux utilizza il metodo `store.subscribe()` per implementare `mapStateToProps()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function `mapStateToProps()`. This function should take `state` as an argument, then return an object which maps that state to specific property names. These properties will become accessible to your component via `props`. Since this example keeps the entire state of the app in a single array, you can pass that entire state to your component. Create a property `messages` in the object that's being returned, and set it to `state`.
|
||||
Crea una funzione `mapStateToProps()`. Questa funzione dovrebbe prendere `state` come argomento, quindi restituire un oggetto che mappa quello stato a specifici nomi di proprietà. Queste proprietà diventeranno accessibili al tuo componente tramite `props`. Dal momento che questo esempio mantiene l'intero stato dell'app in un unico array, è possibile passare l'intero stato al tuo componente. Crea una proprietà `messages` nell'oggetto che viene restituito e impostala a `state`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The const `state` should be an empty array.
|
||||
La costante `state` dovrebbe essere un array vuoto.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(state) && state.length === 0);
|
||||
```
|
||||
|
||||
`mapStateToProps` should be a function.
|
||||
`mapStateToProps` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof mapStateToProps === 'function');
|
||||
```
|
||||
|
||||
`mapStateToProps` should return an object.
|
||||
`mapStateToProps` dovrebbe restituire un oggetto.
|
||||
|
||||
```js
|
||||
assert(typeof mapStateToProps() === 'object');
|
||||
```
|
||||
|
||||
Passing an array as state to `mapStateToProps` should return this array assigned to a key of `messages`.
|
||||
Passare un array come stato a `mapStateToProps` dovrebbe restituire questo array associato a una chiave `messages`.
|
||||
|
||||
```js
|
||||
assert(mapStateToProps(['messages']).messages.pop() === 'messages');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614a
|
||||
title: Moving Forward From Here
|
||||
title: Andare oltre
|
||||
challengeType: 6
|
||||
forumTopicId: 301434
|
||||
dashedName: moving-forward-from-here
|
||||
@ -8,19 +8,19 @@ dashedName: moving-forward-from-here
|
||||
|
||||
# --description--
|
||||
|
||||
Congratulations! You finished the lessons on React and Redux. There's one last item worth pointing out before you move on. Typically, you won't write React apps in a code editor like this. This challenge gives you a glimpse of what the syntax looks like if you're working with npm and a file system on your own machine. The code should look similar, except for the use of `import` statements (these pull in all of the dependencies that have been provided for you in the challenges). The "Managing Packages with npm" section covers npm in more detail.
|
||||
Congratulazioni! Hai finito le lezioni su React e Redux. C'è un ultima cosa che vale la pena di sottolineare prima di andare avanti. In genere, non scriverai le applicazioni React in un editor di codice come questo. Questa sfida ti dà uno sguardo su come appare la sintassi se stai lavorando con npm e un file system sulla tua macchina. Il codice dovrebbe apparire simile, tranne per l'uso delle istruzioni `import` (queste importano tutte le dipendenze che ti sono sono state fornite nelle sfide). La sezione "Gestire i pacchetti con npm" copre npm in maggiore dettaglio.
|
||||
|
||||
Finally, writing React and Redux code generally requires some configuration. This can get complicated quickly. If you are interested in experimenting on your own machine, the <a href="https://github.com/facebookincubator/create-react-app" target="_blank" rel="nofollow">Create React App</a> comes configured and ready to go.
|
||||
Infine, scrivere codice React e Redux richiede generalmente una certa configurazione. Questo può diventare rapidamente complicato. Se sei interessato a sperimentare sulla tua macchina, la <a href="https://github.com/facebookincubator/create-react-app" target="_blank" rel="nofollow">Create React App</a> viene configurata ed è pronta all'uso.
|
||||
|
||||
Alternatively, you can enable Babel as a JavaScript Preprocessor in CodePen, add React and ReactDOM as external JavaScript resources, and work there as well.
|
||||
In alternativa, puoi abilitare Babel come Preprocessore JavaScript in CodePen, aggiungere React e ReactDOM come risorse JavaScript esterne e lavorare anche lì.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Log the message `'Now I know React and Redux!'` to the console.
|
||||
Scrivi il messaggio `'Now I know React and Redux!'` nella console.
|
||||
|
||||
# --hints--
|
||||
|
||||
The message `Now I know React and Redux!` should be logged to the console.
|
||||
Il messaggio `Now I know React and Redux!` dovrebbe essere scritto nella console.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036144
|
||||
title: Use Provider to Connect Redux to React
|
||||
title: Usare il Provider per connettere Redux a React
|
||||
challengeType: 6
|
||||
forumTopicId: 301435
|
||||
dashedName: use-provider-to-connect-redux-to-react
|
||||
@ -8,9 +8,9 @@ dashedName: use-provider-to-connect-redux-to-react
|
||||
|
||||
# --description--
|
||||
|
||||
In the last challenge, you created a Redux store to handle the messages array and created an action for adding new messages. The next step is to provide React access to the Redux store and the actions it needs to dispatch updates. React Redux provides its `react-redux` package to help accomplish these tasks.
|
||||
Nell'ultima sfida, hai creato uno store Redux per gestire l'array dei messaggi e hai creato un'azione per aggiungere nuovi messaggi. Il passo successivo è quello di fornire a React l'accesso allo store di Redux e le azioni di cui ha bisogno per inviare aggiornamenti. React Redux fornisce il suo pacchetto `react-redux` per aiutare a realizzare questi compiti.
|
||||
|
||||
React Redux provides a small API with two key features: `Provider` and `connect`. Another challenge covers `connect`. The `Provider` is a wrapper component from React Redux that wraps your React app. This wrapper then allows you to access the Redux `store` and `dispatch` functions throughout your component tree. `Provider` takes two props, the Redux store and the child components of your app. Defining the `Provider` for an App component might look like this:
|
||||
React Redux fornisce una piccola API con due caratteristiche chiave: `Provider` e `connect`. Un'altra sfida riguarda `connect`. Il `Provider` è un componente wrapper di React Redux che racchiude la tua app React. Questo wrapper consente quindi di accedere alle funzioni dello `store` di Redux e al metodo `dispatch` da tutto il tuo albero dei componenti. `Provider` richiede due proprietà, lo store di Redux e i componenti figli della tua app. La definizione del `Provider` per un componente dell'App potrebbe assomigliare a questa:
|
||||
|
||||
```jsx
|
||||
<Provider store={store}>
|
||||
@ -20,13 +20,13 @@ React Redux provides a small API with two key features: `Provider` and `connect`
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor now shows all your Redux and React code from the past several challenges. It includes the Redux store, actions, and the `DisplayMessages` component. The only new piece is the `AppWrapper` component at the bottom. Use this top level component to render the `Provider` from `ReactRedux`, and pass the Redux store as a prop. Then render the `DisplayMessages` component as a child. Once you are finished, you should see your React component rendered to the page.
|
||||
L'editor di codice ora mostra tutto il tuo codice Redux e React dalle sfide precedenti. Include lo store di Redux, le azioni e il componente `DisplayMessages`. L'unico elemento nuovo è il componente `AppWrapper` in basso. Utilizza questo componente di primo livello per presentare il `Provider` da `ReactRedux`, e passare lo store di Redux come proprietà. Quindi presenta il componente `DisplayMessages` come figlio. Una volta che hai finito, dovresti vedere il tuo componente React presentato nella pagina.
|
||||
|
||||
**Note:** React Redux is available as a global variable here, so you can access the Provider with dot notation. The code in the editor takes advantage of this and sets it to a constant `Provider` for you to use in the `AppWrapper` render method.
|
||||
**Nota:** React Redux è disponibile come variabile globale qui, in modo da poter accedere al Provider con la notazione a punti. Il codice nell'editor sfrutta questa caratteristica e lo imposta a una costante `Provider` da utilizzare nel metodo render di `AppWrapper`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `AppWrapper` should render.
|
||||
Dovrebbe essere avviato il rendering di `AppWrapper`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -37,7 +37,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Provider` wrapper component should have a prop of `store` passed to it, equal to the Redux store.
|
||||
Il componente wrapper `Provider` dovrebbe avere una prop `store` passata ad esso, uguale allo store di Redux.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -51,7 +51,7 @@ The `Provider` wrapper component should have a prop of `store` passed to it, equ
|
||||
);
|
||||
```
|
||||
|
||||
`DisplayMessages` should render as a child of `AppWrapper`.
|
||||
`DisplayMessages` dovrebbe essere presentato come figlio di `AppWrapper`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `DisplayMessages` component should render an `h2`, `input`, `button`, and `ul` element.
|
||||
Il componente `DisplayMessages` dovrebbe presentare gli elementi `h2`, `input`, `button`e `ul`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036154
|
||||
title: Combine Multiple Reducers
|
||||
title: Combinare reducers multipli
|
||||
challengeType: 6
|
||||
forumTopicId: 301436
|
||||
dashedName: combine-multiple-reducers
|
||||
@ -8,11 +8,11 @@ dashedName: combine-multiple-reducers
|
||||
|
||||
# --description--
|
||||
|
||||
When the state of your app begins to grow more complex, it may be tempting to divide state into multiple pieces. Instead, remember the first principle of Redux: all app state is held in a single state object in the store. Therefore, Redux provides reducer composition as a solution for a complex state model. You define multiple reducers to handle different pieces of your application's state, then compose these reducers together into one root reducer. The root reducer is then passed into the Redux `createStore()` method.
|
||||
Quando lo stato della tua app comincia a diventare più complesso, potresti essere tentato di dividere lo stato in più parti. Ricorda invece il primo principio di Redux: tutto lo stato dell'app è tenuto in un singolo oggetto di stato nello store. Detto questo, Redux fornisce la composizione di reducers come soluzione per un modello di stato complesso. Definisci più reducer per gestire diverse parti dello stato della tua applicazione, quindi componi questi reducer insieme in un root reducer (riduttore radice). Il root reducer viene quindi passato nel metodo Redux `createStore()`.
|
||||
|
||||
In order to let us combine multiple reducers together, Redux provides the `combineReducers()` method. This method accepts an object as an argument in which you define properties which associate keys to specific reducer functions. The name you give to the keys will be used by Redux as the name for the associated piece of state.
|
||||
Per farci combinare più reducer insieme, Redux fornisce il metodo `combineReducers()`. Questo metodo accetta come argomento un oggetto in cui si definiscono le proprietà che associano le chiavi a specifiche funzioni reducer. Il nome dato alle chiavi sarà usato da Redux come nome per la parte di stato associata.
|
||||
|
||||
Typically, it is a good practice to create a reducer for each piece of application state when they are distinct or unique in some way. For example, in a note-taking app with user authentication, one reducer could handle authentication while another handles the text and notes that the user is submitting. For such an application, we might write the `combineReducers()` method like this:
|
||||
Tipicamente, è una buona pratica creare un reducer per ogni parte dello stato dell'applicazione quando essi sono distinti o unici in qualche modo. Ad esempio, in un'applicazione per prende appunti con autenticazione dell'utente, un reducer potrebbe gestire l'autenticazione mentre un altro gestisce il testo e le note che l'utente sta scrivendo. Per tale applicazione, potremmo scrivere il metodo `combineReducers()` in questo modo:
|
||||
|
||||
```js
|
||||
const rootReducer = Redux.combineReducers({
|
||||
@ -21,15 +21,15 @@ const rootReducer = Redux.combineReducers({
|
||||
});
|
||||
```
|
||||
|
||||
Now, the key `notes` will contain all of the state associated with our notes and handled by our `notesReducer`. This is how multiple reducers can be composed to manage more complex application state. In this example, the state held in the Redux store would then be a single object containing `auth` and `notes` properties.
|
||||
Ora, la chiave `notes` conterrà tutto lo stato associato alle nostre note e gestito dal nostro `notesReducer`. Questo è il modo in cui più reducer possono essere composti per gestire uno stato dell'applicazione più complesso. In questo esempio, lo stato mantenuto nello store di Redux sarebbe quindi un singolo oggetto contenente le proprietà `auth` e `notes`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are `counterReducer()` and `authReducer()` functions provided in the code editor, along with a Redux store. Finish writing the `rootReducer()` function using the `Redux.combineReducers()` method. Assign `counterReducer` to a key called `count` and `authReducer` to a key called `auth`.
|
||||
Nell'editor di codice trovi le funzioni `counterReducer()` e `authReducer()`, insieme a uno store di Redux. Completa la funzione `rootReducer()` usando il metodo `Redux.combineReducers()`. Assegna `counterReducer` a una chiave denominata `count` e `authReducer` a una chiave denominata `auth`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `counterReducer` should increment and decrement the `state`.
|
||||
Il `counterReducer` dovrebbe aumentare e diminuire lo `state`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,7 +45,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `authReducer` should toggle the `state` of `authenticated` between `true` and `false`.
|
||||
`authReducer` dovrebbe commutare lo `state` di `authenticated` tra `true` e `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -59,7 +59,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The store `state` should have two keys: `count`, which holds a number, and `auth`, which holds an object. The `auth` object should have a property of `authenticated`, which holds a boolean.
|
||||
Lo `state` dello store dovrebbe avere due chiavi: `count`, che contiene un numero, e `auth`, che contiene un oggetto. L'oggetto `auth` dovrebbe avere una proprietà `authenticated`, che contiene un booleano.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -74,7 +74,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `rootReducer` should be a function that combines the `counterReducer` and the `authReducer`.
|
||||
Il `rootReducer` dovrebbe essere una funzione che combina il `counterReducer` e l'`authReducer`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403615b
|
||||
title: Copy an Object with Object.assign
|
||||
title: Copiare un oggetto con Object.assign
|
||||
challengeType: 6
|
||||
forumTopicId: 301437
|
||||
dashedName: copy-an-object-with-object-assign
|
||||
@ -8,21 +8,21 @@ dashedName: copy-an-object-with-object-assign
|
||||
|
||||
# --description--
|
||||
|
||||
The last several challenges worked with arrays, but there are ways to help enforce state immutability when state is an `object`, too. A useful tool for handling objects is the `Object.assign()` utility. `Object.assign()` takes a target object and source objects and maps properties from the source objects to the target object. Any matching properties are overwritten by properties in the source objects. This behavior is commonly used to make shallow copies of objects by passing an empty object as the first argument followed by the object(s) you want to copy. Here's an example:
|
||||
Le ultime sfide funzionavano con gli array, ma ci sono modi per aiutare a far rispettare l'immutabilità dello stato anche quando esso è un `object`. Uno strumento utile per gestire gli oggetti è l'utilità `Object.assign()`. `Object.assign()` prende un oggetto di destinazione e degli oggetti di origine e mappa le proprietà dagli oggetti di origine all'oggetto di destinazione. Tutte le proprietà corrispondenti sono sovrascritte dalle proprietà degli oggetti sorgente. Questo comportamento è comunemente usato per fare copie superficiali di oggetti passando un oggetto vuoto come primo argomento seguito dall'oggetto o dagli oggetti che si desidera copiare. Ecco un esempio:
|
||||
|
||||
```js
|
||||
const newObject = Object.assign({}, obj1, obj2);
|
||||
```
|
||||
|
||||
This creates `newObject` as a new `object`, which contains the properties that currently exist in `obj1` and `obj2`.
|
||||
Questo crea `newObject` come nuovo `object`, che contiene le proprietà che attualmente esistono in `obj1` e `obj2`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The Redux state and actions were modified to handle an `object` for the `state`. Edit the code to return a new `state` object for actions with type `ONLINE`, which set the `status` property to the string `online`. Try to use `Object.assign()` to complete the challenge.
|
||||
Lo stato di Redux e le azioni sono state modificate per gestire un `object` per lo `state`. Modifica il codice per restituire un nuovo oggetto `state` per le azioni di tipo `ONLINE`, che imposta la proprietà `status` sulla stringa `online`. Prova a usare `Object.assign()` per completare la sfida.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should exist and initialize with a state that is equivalent to the `defaultState` object declared on line 1.
|
||||
Lo store Redux dovrebbe esistere ed essere inizializzato con uno stato equivalente all'oggetto `defaultState` dichiarato alla riga 1.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -39,13 +39,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`wakeUp` and `immutableReducer` both should be functions.
|
||||
`wakeUp` e `immutableReducer` dovrebbero essere entrambe funzioni.
|
||||
|
||||
```js
|
||||
assert(typeof wakeUp === 'function' && typeof immutableReducer === 'function');
|
||||
```
|
||||
|
||||
Dispatching an action of type `ONLINE` should update the property `status` in state to `online` and should NOT mutate state.
|
||||
L'invio di un'azione di tipo `ONLINE` dovrebbe aggiornare la proprietà `status` allo stato `online` e NON dovrebbe mutare lo stato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -65,7 +65,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`Object.assign` should be used to return new state.
|
||||
`Object.assign` dovrebbe essere usato per restituire il nuovo stato.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').includes('Object.assign'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614b
|
||||
title: Create a Redux Store
|
||||
title: Creare uno store di Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301439
|
||||
dashedName: create-a-redux-store
|
||||
@ -8,29 +8,29 @@ dashedName: create-a-redux-store
|
||||
|
||||
# --description--
|
||||
|
||||
Redux is a state management framework that can be used with a number of different web technologies, including React.
|
||||
Redux è un framework di gestione dello stato che può essere utilizzato con una serie di diverse tecnologie web, tra cui React.
|
||||
|
||||
In Redux, there is a single state object that's responsible for the entire state of your application. This means if you had a React app with ten components, and each component had its own local state, the entire state of your app would be defined by a single state object housed in the Redux `store`. This is the first important principle to understand when learning Redux: the Redux store is the single source of truth when it comes to application state.
|
||||
In Redux c'è un singolo oggetto di stato che è responsabile per l'intero stato della tua applicazione. Ciò significa che se hai un'app React con dieci componenti, e ogni componente aveva il proprio stato locale, l'intero stato della tua app sarà definito da un singolo oggetto di stato ospitato nello `store` di Redux. Questo è il primo principio importante da capire quando si studia Redux: lo store di Redux è la singola fonte di verità quando si tratta di stato dell'applicazione.
|
||||
|
||||
This also means that any time any piece of your app wants to update state, it **must** do so through the Redux store. The unidirectional data flow makes it easier to track state management in your app.
|
||||
Questo significa anche che ogni volta che una parte della tua app vuole aggiornare lo stato, essa **deve** farlo attraverso lo store di Redux. Il flusso di dati unidirezionale rende più facile monitorare la gestione dello stato nella tua app.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The Redux `store` is an object which holds and manages application `state`. There is a method called `createStore()` on the Redux object, which you use to create the Redux `store`. This method takes a `reducer` function as a required argument. The `reducer` function is covered in a later challenge, and is already defined for you in the code editor. It simply takes `state` as an argument and returns `state`.
|
||||
Lo `store` di Redux è un oggetto che detiene e gestisce lo `state` dell'applicazione. Nell'oggetto Redux c'è un metodo chiamato `createStore()` che si usa per creare lo `store` di Redux. Questo metodo prende una funzione `reducer` come argomento richiesto. La funzione `reducer` è spiegata da una sfida successiva, ed è già definita per te nell'editor di codice. Essa richiede semplicemente `state` come argomento e restituisce `state`.
|
||||
|
||||
Declare a `store` variable and assign it to the `createStore()` method, passing in the `reducer` as an argument.
|
||||
Dichiara una variabile `store` e assegnala al metodo `createStore()`, passando il `reducer` come argomento.
|
||||
|
||||
**Note:** The code in the editor uses ES6 default argument syntax to initialize this state to hold a value of `5`. If you're not familiar with default arguments, you can refer to the [ES6 section in the Curriculum](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions) which covers this topic.
|
||||
**Nota:** Il codice nell'editor utilizza la sintassi predefinita degli argomenti ES6 per inizializzare questo stato in modo da contenere un valore di `5`. Se non hai familiarità con gli argomenti predefiniti, puoi fare riferimento alla [sezione ES6 nel Curriculum](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions) che copre questo argomento.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should exist.
|
||||
Lo store di Redux dovrebbe esistere.
|
||||
|
||||
```js
|
||||
assert(typeof store.getState === 'function');
|
||||
```
|
||||
|
||||
The Redux store should have a value of 5 for the state.
|
||||
Lo store di Redux dovrebbe avere un valore di 5 per lo stato.
|
||||
|
||||
```js
|
||||
assert(store.getState() === 5);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614d
|
||||
title: Define a Redux Action
|
||||
title: Definire un'azione Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301440
|
||||
dashedName: define-a-redux-action
|
||||
@ -8,17 +8,17 @@ dashedName: define-a-redux-action
|
||||
|
||||
# --description--
|
||||
|
||||
Since Redux is a state management framework, updating state is one of its core tasks. In Redux, all state updates are triggered by dispatching actions. An action is simply a JavaScript object that contains information about an action event that has occurred. The Redux store receives these action objects, then updates its state accordingly. Sometimes a Redux action also carries some data. For example, the action carries a username after a user logs in. While the data is optional, actions must carry a `type` property that specifies the 'type' of action that occurred.
|
||||
Dal momento che Redux è un framework di gestione dello stato, l'aggiornamento dello stato è uno dei suoi compiti fondamentali. In Redux, tutti gli aggiornamenti di stato vengono attivati dalle azioni di dispatching (invio). Un'azione è semplicemente un oggetto JavaScript che contiene informazioni su un evento di azione che si è verificato. Lo store Redux riceve questi oggetti di azione, quindi aggiorna il suo stato di conseguenza. A volte un'azione Redux contiene anche dei dati. Ad esempio, l'azione contiene uno username dopo il login di un utente. Mentre i dati sono facoltativi, le azioni devono contenere una proprietà `type` che specifica il 'tipo' di azione che si è verificato.
|
||||
|
||||
Think of Redux actions as messengers that deliver information about events happening in your app to the Redux store. The store then conducts the business of updating state based on the action that occurred.
|
||||
Pensa alle azioni Redux come a messaggeri che portano informazioni sugli eventi che accadono nella tua app allo store di Redux. Lo store conduce poi l'attività di aggiornamento dello stato in base all'azione che si è verificata.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Writing a Redux action is as simple as declaring an object with a type property. Declare an object `action` and give it a property `type` set to the string `'LOGIN'`.
|
||||
Scrivere un'azione Redux è semplice come dichiarare un oggetto con una proprietà type. Dichiara un oggetto `action` e dagli una proprietà `type` impostata alla stringa `'LOGIN'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
An `action` object should exist.
|
||||
Dovrebbe esistere un oggetto `action`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -28,7 +28,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `action` object should have a key property `type` with value `LOGIN`.
|
||||
L'oggetto `action` dovrebbe avere una proprietà `type` con valore `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614e
|
||||
title: Define an Action Creator
|
||||
title: Definire un creatore di azione
|
||||
challengeType: 6
|
||||
forumTopicId: 301441
|
||||
dashedName: define-an-action-creator
|
||||
@ -8,27 +8,27 @@ dashedName: define-an-action-creator
|
||||
|
||||
# --description--
|
||||
|
||||
After creating an action, the next step is sending the action to the Redux store so it can update its state. In Redux, you define action creators to accomplish this. An action creator is simply a JavaScript function that returns an action. In other words, action creators create objects that represent action events.
|
||||
Dopo aver creato un'azione, il passo successivo è l'invio dell'azione allo store di Redux in modo che possa aggiornare il suo stato. Per farlo, in Redux si definiscono i creatori di azione. Un creatore di azione è semplicemente una funzione JavaScript che restituisce un'azione. In altre parole, i creatori di azione creano oggetti che rappresentano gli eventi di azione.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define a function named `actionCreator()` that returns the `action` object when called.
|
||||
Definisci una funzione `actionCreator()` che restituisce l'oggetto `action` quando chiamata.
|
||||
|
||||
# --hints--
|
||||
|
||||
The function `actionCreator` should exist.
|
||||
La funzione `actionCreator` dovrebbe esistere.
|
||||
|
||||
```js
|
||||
assert(typeof actionCreator === 'function');
|
||||
```
|
||||
|
||||
Running the `actionCreator` function should return the `action` object.
|
||||
L'esecuzione della funzione `actionCreator` dovrebbe restituire l'oggetto `action`.
|
||||
|
||||
```js
|
||||
assert(typeof action === 'object');
|
||||
```
|
||||
|
||||
The returned `action` should have a key property `type` with value `LOGIN`.
|
||||
L'`action` restituita dovrebbe avere una proprietà di chiave `type` con valore `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(action.type === 'LOGIN');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614f
|
||||
title: Dispatch an Action Event
|
||||
title: Inviare un evento azione
|
||||
challengeType: 6
|
||||
forumTopicId: 301442
|
||||
dashedName: dispatch-an-action-event
|
||||
@ -8,9 +8,9 @@ dashedName: dispatch-an-action-event
|
||||
|
||||
# --description--
|
||||
|
||||
`dispatch` method is what you use to dispatch actions to the Redux store. Calling `store.dispatch()` and passing the value returned from an action creator sends an action back to the store.
|
||||
Il metodo `dispatch` è quello che usi per inviare azioni allo store Redux. Chiamando `store.dispatch()` e passando il valore restituito da un creatore di azione, un'azione viene inviata di rimando allo store.
|
||||
|
||||
Recall that action creators return an object with a type property that specifies the action that has occurred. Then the method dispatches an action object to the Redux store. Based on the previous challenge's example, the following lines are equivalent, and both dispatch the action of type `LOGIN`:
|
||||
Ricorda che i creatori di azione restituiscono un oggetto con una proprietà type che specifica l'azione che si è verificata. Quindi il metodo invia un oggetto di azione allo store di Redux. Sulla base dell'esempio della sfida precedente, le seguenti righe sono equivalenti, ed entrambe inviano l'azione di tipo `LOGIN`:
|
||||
|
||||
```js
|
||||
store.dispatch(actionCreator());
|
||||
@ -19,23 +19,23 @@ store.dispatch({ type: 'LOGIN' });
|
||||
|
||||
# --instructions--
|
||||
|
||||
The Redux store in the code editor has an initialized state that's an object containing a `login` property currently set to `false`. There's also an action creator called `loginAction()` which returns an action of type `LOGIN`. Dispatch the `LOGIN` action to the Redux store by calling the `dispatch` method, and pass in the action created by `loginAction()`.
|
||||
Lo store Redux nell'editor di codice ha uno stato inizializzato con un oggetto contenente una proprietà `login`, attualmente impostata a `false`. C'è anche un creatore di azione denominato `loginAction()` che restituisce un'azione di tipo `LOGIN`. Invia l'azione `LOGIN` allo store Redux chiamando il metodo `dispatch`, e passandole l'azione creata da `loginAction()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Calling the function `loginAction` should return an object with `type` property set to the string `LOGIN`.
|
||||
Chiamare la funzione `loginAction` dovrebbe restituire un oggetto con la proprietà `type` impostata alla stringa `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(loginAction().type === 'LOGIN');
|
||||
```
|
||||
|
||||
The store should be initialized with an object with property `login` set to `false`.
|
||||
Lo store dovrebbe essere inizializzato con un oggetto con proprietà `login` impostata su `false`.
|
||||
|
||||
```js
|
||||
assert(store.getState().login === false);
|
||||
```
|
||||
|
||||
The `store.dispatch()` method should be used to dispatch an action of type `LOGIN`.
|
||||
Il metodo `store.dispatch()` dovrebbe essere utilizzato per inviare un'azione di tipo `LOGIN`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403614c
|
||||
title: Get State from the Redux Store
|
||||
title: Ottenere lo stato dallo store di Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301443
|
||||
dashedName: get-state-from-the-redux-store
|
||||
@ -8,21 +8,21 @@ dashedName: get-state-from-the-redux-store
|
||||
|
||||
# --description--
|
||||
|
||||
The Redux store object provides several methods that allow you to interact with it. For example, you can retrieve the current `state` held in the Redux store object with the `getState()` method.
|
||||
L'oggetto store di Redux fornisce diversi metodi che consentono di interagire con esso. Ad esempio, è possibile recuperare lo `state` attuale contenuto nell'oggetto store di Redux con il metodo `getState()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code from the previous challenge is re-written more concisely in the code editor. Use `store.getState()` to retrieve the `state` from the `store`, and assign this to a new variable `currentState`.
|
||||
Il codice della sfida precedente viene riscritto più concisamente nell'editor di codice. Usa `store.getState()` per recuperare lo `state` dallo `store`, e assegnarlo a una nuova variabile `currentState`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should have a value of 5 for the initial state.
|
||||
Lo store di Redux dovrebbe avere un valore di 5 come stato iniziale.
|
||||
|
||||
```js
|
||||
assert(store.getState() === 5);
|
||||
```
|
||||
|
||||
A variable `currentState` should exist and should be assigned the current state of the Redux store.
|
||||
Una variabile `currentState` dovrebbe esistere e dovrebbe esserle assegnato lo stato corrente dello store di Redux.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036150
|
||||
title: Handle an Action in the Store
|
||||
title: Gestire un'azione nello store
|
||||
challengeType: 6
|
||||
forumTopicId: 301444
|
||||
dashedName: handle-an-action-in-the-store
|
||||
@ -8,29 +8,29 @@ dashedName: handle-an-action-in-the-store
|
||||
|
||||
# --description--
|
||||
|
||||
After an action is created and dispatched, the Redux store needs to know how to respond to that action. This is the job of a `reducer` function. Reducers in Redux are responsible for the state modifications that take place in response to actions. A `reducer` takes `state` and `action` as arguments, and it always returns a new `state`. It is important to see that this is the **only** role of the reducer. It has no side effects — it never calls an API endpoint and it never has any hidden surprises. The reducer is simply a pure function that takes state and action, then returns new state.
|
||||
Dopo che un'azione è stata creata e spedita, lo store di Redux deve sapere come rispondere a quell'azione. Questo è il lavoro di una funzione `reducer` (riduttore). I reducer in Redux sono responsabili delle modifiche allo stato che si verificano in risposta alle azioni. Un `reducer` prende `state` e `action` come argomenti, e restituisce sempre un nuovo `state`. È importante capire che questo è l'**unico** ruolo del reducer. Questo non ha effetti collaterali - non chiama mai un endpoint API e non ha mai sorprese nascoste. Il reducer è semplicemente una funzione pura che prende uno stato e un'azione, e restituisce un nuovo stato.
|
||||
|
||||
Another key principle in Redux is that `state` is read-only. In other words, the `reducer` function must **always** return a new copy of `state` and never modify state directly. Redux does not enforce state immutability, however, you are responsible for enforcing it in the code of your reducer functions. You'll practice this in later challenges.
|
||||
Un altro principio chiave in Redux è che lo `state` è di sola lettura. In altre parole, la funzione `reducer` deve **sempre** restituire una nuova copia dello `state` e non modificare mai direttamente lo state. Redux non applica l'immutabilità dello stato, tuttavia sei responsabile di applicarlo nel codice delle tue funzioni reducer. Nelle prossime sfide farai pratica con questo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has the previous example as well as the start of a `reducer` function for you. Fill in the body of the `reducer` function so that if it receives an action of type `'LOGIN'` it returns a state object with `login` set to `true`. Otherwise, it returns the current `state`. Note that the current `state` and the dispatched `action` are passed to the reducer, so you can access the action's type directly with `action.type`.
|
||||
L'editor di codice contiene l'esempio precedente e l'inizio di una funzione `reducer` pronti per te. Compila il corpo della funzione `reducer` in modo che se riceve un'azione di tipo `'LOGIN'` restituisca un oggetto stato con `login` impostato a `true`. Altrimenti, restituisce lo `state` attuale. Nota che lo `state` corrente e l'`action` inviata sono passati al reducer, in modo da poter accedere direttamente al tipo di azione con `action.type`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Calling the function `loginAction` should return an object with type property set to the string `LOGIN`.
|
||||
Chiamare la funzione `loginAction` dovrebbe restituire un oggetto con proprietà type impostata sulla stringa `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(loginAction().type === 'LOGIN');
|
||||
```
|
||||
|
||||
The store should be initialized with an object with property `login` set to `false`.
|
||||
Lo store dovrebbe essere inizializzato con un oggetto con proprietà `login` impostata su `false`.
|
||||
|
||||
```js
|
||||
assert(store.getState().login === false);
|
||||
```
|
||||
|
||||
Dispatching `loginAction` should update the `login` property in the store state to `true`.
|
||||
Inviare `loginAction` dovrebbe aggiornare la proprietà `login` nello stato dello store a `true`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,7 +43,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
If the action is not of type `LOGIN`, the store should return the current state.
|
||||
Se l'azione non è di tipo `LOGIN`, lo store dovrebbe restituire lo stato corrente.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036158
|
||||
title: Never Mutate State
|
||||
title: Mai mutare lo stato
|
||||
challengeType: 6
|
||||
forumTopicId: 301445
|
||||
dashedName: never-mutate-state
|
||||
@ -8,19 +8,19 @@ dashedName: never-mutate-state
|
||||
|
||||
# --description--
|
||||
|
||||
These final challenges describe several methods of enforcing the key principle of state immutability in Redux. Immutable state means that you never modify state directly, instead, you return a new copy of state.
|
||||
Queste ultime sfide descrivono diversi metodi per far rispettare il principio fondamentale dell'immutabilità dello stato in Redux. Immutabilità dello stato significa che non si modifica mai direttamente lo stato, ma si restituisce una nuova copia di esso.
|
||||
|
||||
If you took a snapshot of the state of a Redux app over time, you would see something like `state 1`, `state 2`, `state 3`,`state 4`, `...` and so on where each state may be similar to the last, but each is a distinct piece of data. This immutability, in fact, is what provides such features as time-travel debugging that you may have heard about.
|
||||
Se scattassi un'istantanea dello stato di un'applicazione Redux nel tempo, vedresti qualcosa come `state 1`, `state 2`, `state 3`,`state 4`, `...` e così via dove ogni stato può essere simile al precedente, ma ognuno è un dato distinto. Questa immutabilità, infatti, è ciò che fornisce caratteristiche come il debugging time-travel (viaggio nel tempo) di cui potresti aver sentito parlare.
|
||||
|
||||
Redux does not actively enforce state immutability in its store or reducers, that responsibility falls on the programmer. Fortunately, JavaScript (especially ES6) provides several useful tools you can use to enforce the immutability of your state, whether it is a `string`, `number`, `array`, or `object`. Note that strings and numbers are primitive values and are immutable by nature. In other words, 3 is always 3. You cannot change the value of the number 3. An `array` or `object`, however, is mutable. In practice, your state will probably consist of an `array` or `object`, as these are useful data structures for representing many types of information.
|
||||
Redux non applica attivamente l'immutabilità dello stato nel suo store o nei reducer: questa responsabilità ricade sul programmatore. Fortunatamente, JavaScript (specialmente ES6) fornisce diversi strumenti utili che puoi usare per far rispettare l'immutabilità del tuo stato, che si tratti di una `string`, `number`, `array` o `object`. Nota che le stringhe e i numeri sono valori primitivi e sono immutabili per natura. In altre parole, 3 è sempre 3. Non è possibile modificare il valore del numero 3. Un `array` o `object`, invece, è mutabile. In pratica, il tuo stato sarà probabilmente costituito da un `array` o da un `object`, trattandosi di strutture di dati utili per rappresentare molti tipi di informazioni.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There is a `store` and `reducer` in the code editor for managing to-do items. Finish writing the `ADD_TO_DO` case in the reducer to append a new to-do to the state. There are a few ways to accomplish this with standard JavaScript or ES6. See if you can find a way to return a new array with the item from `action.todo` appended to the end.
|
||||
Nell'editor di codice ci sono uno `store` e un `reducer` per gestire gli elementi della lista to-do. Termina la scrittura del caso `ADD_TO_DO` nel reducer per aggiungere una nuova cosa da fare allo stato. Ci sono alcuni modi per realizzarlo con standard JavaScript o ES6. Vedi se puoi trovare un modo per restituire un nuovo array con l'elemento preso da `action.todo` aggiunto alla fine.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should exist and initialize with a state equal to the `todos` array in the code editor.
|
||||
Lo store Redux dovrebbe esistere ed essere inizializzato con uno stato uguale all'array `todos` nell'editor di codice.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -39,13 +39,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`addToDo` and `immutableReducer` both should be functions.
|
||||
`addToDo` e `immutableReducer` dovrebbero essere entrambe funzioni.
|
||||
|
||||
```js
|
||||
assert(typeof addToDo === 'function' && typeof immutableReducer === 'function');
|
||||
```
|
||||
|
||||
Dispatching an action of type `ADD_TO_DO` on the Redux store should add a `todo` item and should NOT mutate state.
|
||||
L'invio di un'azione di tipo `ADD_TO_DO` allo store di Redux dovrebbe aggiungere un elemento `todo` e NON dovrebbe mutare lo stato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036153
|
||||
title: Register a Store Listener
|
||||
title: Registrare un listener dello store
|
||||
challengeType: 6
|
||||
forumTopicId: 301446
|
||||
dashedName: register-a-store-listener
|
||||
@ -8,15 +8,15 @@ dashedName: register-a-store-listener
|
||||
|
||||
# --description--
|
||||
|
||||
Another method you have access to on the Redux `store` object is `store.subscribe()`. This allows you to subscribe listener functions to the store, which are called whenever an action is dispatched against the store. One simple use for this method is to subscribe a function to your store that simply logs a message every time an action is received and the store is updated.
|
||||
Un altro metodo a cui hai accesso dall'oggetto `store` di Redux è `store.subscribe()`. Questo ti permette di iscrivere delle funzioni listener (di ascolto) nello store, che vengono chiamate ogni volta che un'azione viene spedita allo store. Un semplice utilizzo per questo metodo è quello di iscrivere una funzione al tuo store, in modo che registri semplicemente un messaggio ogni volta che un'azione viene ricevuta e lo store viene aggiornato.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a callback function that increments the global variable `count` every time the store receives an action, and pass this function in to the `store.subscribe()` method. You'll see that `store.dispatch()` is called three times in a row, each time directly passing in an action object. Watch the console output between the action dispatches to see the updates take place.
|
||||
Scrivi una funzione di callback che incrementa la variabile globale `count` ogni volta che lo store riceve un'azione, e passa questa funzione al metodo `store.subscribe()`. Vedrai che `store.dispatch()` è chiamato tre volte di fila, ogni volta che passa direttamente in un oggetto azione. Guarda l'output della console tra le azioni inviate per vedere gli aggiornamenti effettuati.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dispatching the `ADD` action on the store should increment the state by `1`.
|
||||
La spedizione dell'azione `ADD` allo store dovrebbe aumentare lo stato di `1`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -29,19 +29,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
There should be a listener function subscribed to the store using `store.subscribe`.
|
||||
Dovrebbe esserci una funzione listener iscritta allo store usando `store.subscribe`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/store\s*\.\s*subscribe\(/gm));
|
||||
```
|
||||
|
||||
The `store.subscribe` should receive a function.
|
||||
`store.subscribe` dovrebbe ricevere una funzione.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(\s*function\s*)|(\s*\(\s*\)\s*=>)/gm))
|
||||
```
|
||||
|
||||
The callback to `store.subscribe` should also increment the global `count` variable as the store is updated.
|
||||
La callback `store.subscribe` dovrebbe anche aumentare la variabile globale `count` quando lo store viene aggiornato.
|
||||
|
||||
```js
|
||||
assert(store.getState() === count);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403615a
|
||||
title: Remove an Item from an Array
|
||||
title: Rimuovere un elemento da un Array
|
||||
challengeType: 6
|
||||
forumTopicId: 301447
|
||||
dashedName: remove-an-item-from-an-array
|
||||
@ -8,15 +8,15 @@ dashedName: remove-an-item-from-an-array
|
||||
|
||||
# --description--
|
||||
|
||||
Time to practice removing items from an array. The spread operator can be used here as well. Other useful JavaScript methods include `slice()` and `concat()`.
|
||||
È ora di fare pratica con la rimozione di elementi da un array. L'operatore di propagazione può essere utilizzato anche qui. Altri utili metodi JavaScript includono `slice()` e `concat()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The reducer and action creator were modified to remove an item from an array based on the index of the item. Finish writing the reducer so a new state array is returned with the item at the specific index removed.
|
||||
Il reducer e il creatore di azione sono stati modificati per rimuovere un elemento da un array in base all'indice dell'elemento. Termina la scrittura del reducer in modo che un nuovo array di stato venga restituito senza l'elemento all'indice specificato.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should exist and initialize with a state equal to `[0,1,2,3,4,5]`
|
||||
Lo store di Redux dovrebbe esistere ed essere inizializzato con uno stato uguale a `[0,1,2,3,4,5]`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`removeItem` and `immutableReducer` both should be functions.
|
||||
`removeItem` e `immutableReducer` dovrebbero essere entrambe funzioni.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching the `removeItem` action creator should remove items from the state and should NOT mutate state.
|
||||
La spedizione del creatore di azione `removeItem` dovrebbe rimuovere gli elementi dallo stato e NON dovrebbe mutare lo stato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036155
|
||||
title: Send Action Data to the Store
|
||||
title: Inviare i dati delle azioni allo store
|
||||
challengeType: 6
|
||||
forumTopicId: 301448
|
||||
dashedName: send-action-data-to-the-store
|
||||
@ -8,19 +8,19 @@ dashedName: send-action-data-to-the-store
|
||||
|
||||
# --description--
|
||||
|
||||
By now you've learned how to dispatch actions to the Redux store, but so far these actions have not contained any information other than a `type`. You can also send specific data along with your actions. In fact, this is very common because actions usually originate from some user interaction and tend to carry some data with them. The Redux store often needs to know about this data.
|
||||
Finora hai imparato come inviare azioni allo store Redux, ma queste azioni non contenevano alcuna informazione diversa da un `type`. Puoi anche inviare dati specifici insieme alle tue azioni. In realtà, questo è molto comune perché le azioni di solito provengono da alcune interazioni dell'utente e tendono a portare dei dati con loro. Lo store di Redux ha spesso bisogno di conoscere questi dati.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There's a basic `notesReducer()` and an `addNoteText()` action creator defined in the code editor. Finish the body of the `addNoteText()` function so that it returns an `action` object. The object should include a `type` property with a value of `ADD_NOTE`, and also a `text` property set to the `note` data that's passed into the action creator. When you call the action creator, you'll pass in specific note information that you can access for the object.
|
||||
Nell'editor di codice ci sono un `notesReducer()` di base e un creatore di azione `addNoteText()`. Termina il corpo della funzione `addNoteText()` in modo che restituisca un oggetto `action`. L'oggetto dovrebbe includere una proprietà `type` con un valore di `ADD_NOTE`, e anche una proprietà `text` impostata al dato `note` passato al creatore di azione. Quando chiami il creatore di azione, passi specifiche informazioni alle quali puoi accedere per l'oggetto.
|
||||
|
||||
Next, finish writing the `switch` statement in the `notesReducer()`. You need to add a case that handles the `addNoteText()` actions. This case should be triggered whenever there is an action of type `ADD_NOTE` and it should return the `text` property on the incoming `action` as the new `state`.
|
||||
Successivamente, termina la scrittura dell'istruzione `switch` in `notesReducer()`. Dovrai aggiungere un caso che gestisca le azioni `addNoteText()`. Questo caso dovrebbe essere attivato ogni volta che c'è un'azione di tipo `ADD_NOTE` e dovrebbe restituire la proprietà `text` dell'`action` in arrivo come nuovo `state`.
|
||||
|
||||
The action is dispatched at the bottom of the code. Once you're finished, run the code and watch the console. That's all it takes to send action-specific data to the store and use it when you update store `state`.
|
||||
L'azione viene spedita nella parte finale del codice. Una volta finito, esegui il codice e guarda la console. Questo è tutto ciò che serve per inviare dati specifici dell'azione allo store e usarli quando aggiorni lo `state` dello store.
|
||||
|
||||
# --hints--
|
||||
|
||||
The action creator `addNoteText` should return an object with keys `type` and `text`.
|
||||
Il creatore di azioni `addNoteText` dovrebbe restituire un oggetto con chiavi `type` e `text`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching an action of type `ADD_NOTE` with the `addNoteText` action creator should update the `state` to the string passed to the action creator.
|
||||
La spedizione di un'azione di tipo `ADD_NOTE` con il creatore di azione `addNoteText` dovrebbe aggiornare lo `state` alla stringa passata al creatore dell'azione.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036151
|
||||
title: Use a Switch Statement to Handle Multiple Actions
|
||||
title: Usare un'istruzione switch per gestire più azioni
|
||||
challengeType: 6
|
||||
forumTopicId: 301449
|
||||
dashedName: use-a-switch-statement-to-handle-multiple-actions
|
||||
@ -8,35 +8,35 @@ dashedName: use-a-switch-statement-to-handle-multiple-actions
|
||||
|
||||
# --description--
|
||||
|
||||
You can tell the Redux store how to handle multiple action types. Say you are managing user authentication in your Redux store. You want to have a state representation for when users are logged in and when they are logged out. You represent this with a single state object with the property `authenticated`. You also need action creators that create actions corresponding to user login and user logout, along with the action objects themselves.
|
||||
È possibile dire allo store di Redux come gestire diversi tipi di azione. Diciamo che tu debba gestire l'autenticazione dell'utente nel tuo store di Redux. Vuoi avere una rappresentazione dello stato per quando gli utenti sono connessi e per quando sono disconnessi. Lo rappresenti con un singolo oggetto di stato con la proprietà `authenticated`. Hai anche bisogno di creatori di azione che creino azioni corrispondenti al login e al logout dell'utente, insieme agli oggetti azione stessi.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has a store, actions, and action creators set up for you. Fill in the `reducer` function to handle multiple authentication actions. Use a JavaScript `switch` statement in the `reducer` to respond to different action events. This is a standard pattern in writing Redux reducers. The switch statement should switch over `action.type` and return the appropriate authentication state.
|
||||
L'editor di codice ha già uno store, delle azioni e dei creatori di azioni configurati per te. Completa la funzione `reducer` perché gestisca più azioni di autenticazione. Usa un'istruzione JavaScript `switch` nel `reducer` per rispondere a diversi eventi di azione. Questo è un modello standard nella scrittura di reducer Redux. L'istruzione switch dovrebbe smistare in base a `action.type` e restituire lo stato di autenticazione appropriato.
|
||||
|
||||
**Note:** At this point, don't worry about state immutability, since it is small and simple in this example. For each action, you can return a new object — for example, `{authenticated: true}`. Also, don't forget to write a `default` case in your switch statement that returns the current `state`. This is important because once your app has multiple reducers, they are all run any time an action dispatch is made, even when the action isn't related to that reducer. In such a case, you want to make sure that you return the current `state`.
|
||||
**Nota:** Non preoccuparti per l'immutabilità dello stato, dato che è piccolo e semplice in questo esempio. Per ogni azione, puoi restituire un nuovo oggetto — per esempio, `{authenticated: true}`. Inoltre, non dimenticare di scrivere un caso di `default` nella tua istruzione switch che restituisca lo `state` corrente. Questo è importante perché una volta che l'app ha più reducer, essi vengono eseguiti tutti ogni volta che viene spedita un'azione, anche quando l'azione non è correlata a quel reducer. In questo caso, vuoi assicurarti di restituire lo `state` corrente.
|
||||
|
||||
# --hints--
|
||||
|
||||
Calling the function `loginUser` should return an object with type property set to the string `LOGIN`.
|
||||
Chiamando la funzione `loginUser` dovrebbe essere restituito un oggetto con proprietà type impostata alla stringa `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(loginUser().type === 'LOGIN');
|
||||
```
|
||||
|
||||
Calling the function `logoutUser` should return an object with type property set to the string `LOGOUT`.
|
||||
Chiamando la funzione `logoutUser` dovrebbe essere restituito un oggetto con proprietà type impostata alla stringa `LOGOUT`.
|
||||
|
||||
```js
|
||||
assert(logoutUser().type === 'LOGOUT');
|
||||
```
|
||||
|
||||
The store should be initialized with an object with an `authenticated` property set to `false`.
|
||||
Lo store dovrebbe essere inizializzato con un oggetto con una proprietà `authenticated` impostata a `false`.
|
||||
|
||||
```js
|
||||
assert(store.getState().authenticated === false);
|
||||
```
|
||||
|
||||
Dispatching `loginUser` should update the `authenticated` property in the store state to `true`.
|
||||
L'invio di `loginUser` dovrebbe impostare a `true` la proprietà `authenticated` nello stato dello store.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching `logoutUser` should update the `authenticated` property in the store state to `false`.
|
||||
La spedizione di `logoutUser` dovrebbe impostare a `false` la proprietà `authenticated` nello stato dello store.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -67,7 +67,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `authReducer` function should handle multiple action types with a `switch` statement.
|
||||
La funzione `authReducer` dovrebbe gestire più tipi di azione con un'istruzione `switch`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036152
|
||||
title: Use const for Action Types
|
||||
title: Usare const per i tipi di azione
|
||||
challengeType: 6
|
||||
forumTopicId: 301450
|
||||
dashedName: use-const-for-action-types
|
||||
@ -8,35 +8,35 @@ dashedName: use-const-for-action-types
|
||||
|
||||
# --description--
|
||||
|
||||
A common practice when working with Redux is to assign action types as read-only constants, then reference these constants wherever they are used. You can refactor the code you're working with to write the action types as `const` declarations.
|
||||
Una pratica comune quando si lavora con Redux è quella di assegnare i tipi di azione come costanti di sola lettura, quindi fare riferimento a queste costanti ovunque siano usate. Puoi rivedere il codice con cui stai lavorando per scrivere i tipi di azione come dichiarazioni `const`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Declare `LOGIN` and `LOGOUT` as `const` values and assign them to the strings `'LOGIN'` and `'LOGOUT'`, respectively. Then, edit the `authReducer()` and the action creators to reference these constants instead of string values.
|
||||
Dichiara `LOGIN` e `LOGOUT` come valori `const` e assegnali rispettivamente alle stringhe `'LOGIN'` e `'LOGOUT'`. Quindi, modifica `authReducer()` e i creatori di azione in modo che facciano riferimento a queste costanti invece che ai valori stringa.
|
||||
|
||||
**Note:** It's generally a convention to write constants in all uppercase, and this is standard practice in Redux as well.
|
||||
**Nota:** È una convenzione generale scrivere le costanti tutte in maiuscolo e questa è la pratica standard anche in Redux.
|
||||
|
||||
# --hints--
|
||||
|
||||
Calling the function `loginUser` should return an object with `type` property set to the string `LOGIN`.
|
||||
Chiamando la funzione `loginUser` dovrebbe essere restituito un oggetto con la proprietà `type` impostata alla stringa `LOGIN`.
|
||||
|
||||
```js
|
||||
assert(loginUser().type === 'LOGIN');
|
||||
```
|
||||
|
||||
Calling the function `logoutUser` should return an object with `type` property set to the string `LOGOUT`.
|
||||
Chiamando la funzione `logoutUser` dovrebbe essere restituito un oggetto con la proprietà `type` impostata alla stringa `LOGOUT`.
|
||||
|
||||
```js
|
||||
assert(logoutUser().type === 'LOGOUT');
|
||||
```
|
||||
|
||||
The store should be initialized with an object with property `login` set to `false`.
|
||||
Lo store dovrebbe essere inizializzato con un oggetto con proprietà `login` impostata su `false`.
|
||||
|
||||
```js
|
||||
assert(store.getState().authenticated === false);
|
||||
```
|
||||
|
||||
Dispatching `loginUser` should update the `login` property in the store state to `true`.
|
||||
Il dispatch di `loginUser` dovrebbe impostare a `true` la proprietà `login` nello stato dello store.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching `logoutUser` should update the `login` property in the store state to `false`.
|
||||
Il dispatch di `logoutUser` dovrebbe impostare a `false` la proprietà `login` nello stato dello store.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -67,7 +67,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `authReducer` function should handle multiple action types with a switch statement.
|
||||
La funzione `authReducer` dovrebbe gestire più tipi di azione con un'istruzione switch.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -83,17 +83,18 @@ The `authReducer` function should handle multiple action types with a switch sta
|
||||
);
|
||||
```
|
||||
|
||||
`LOGIN` and `LOGOUT` should be declared as `const` values and should be assigned strings of `LOGIN`and `LOGOUT`.
|
||||
`LOGIN` e `LOGOUT` dovrebbero essere dichiarati come valori `const` e dovrebbero essere assegnate loro le stringhe `LOGIN` e `LOGOUT`.
|
||||
|
||||
```js
|
||||
const noWhiteSpace = __helpers.removeWhiteSpace(code);
|
||||
assert(
|
||||
/constLOGIN=(['"`])LOGIN\1/.test(noWhiteSpace) &&
|
||||
/constLOGOUT=(['"`])LOGOUT\1/.test(noWhiteSpace)
|
||||
(/constLOGIN=(['"`])LOGIN\1/.test(noWhiteSpace) &&
|
||||
/constLOGOUT=(['"`])LOGOUT\1/.test(noWhiteSpace)) ||
|
||||
/const(LOGIN|LOGOUT)=(['"`])\1\2,(?!\1)(LOGIN|LOGOUT)=(['"`])\3\4/.test(noWhiteSpace)
|
||||
);
|
||||
```
|
||||
|
||||
The action creators and the reducer should reference the `LOGIN` and `LOGOUT` constants.
|
||||
I creatori di azioni e il reducer dovrebbero fare riferimento alle costanti `LOGIN` e `LOGOUT`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036156
|
||||
title: Use Middleware to Handle Asynchronous Actions
|
||||
title: Usare il middleware per gestire azioni asincrone
|
||||
challengeType: 6
|
||||
forumTopicId: 301451
|
||||
dashedName: use-middleware-to-handle-asynchronous-actions
|
||||
@ -8,39 +8,39 @@ dashedName: use-middleware-to-handle-asynchronous-actions
|
||||
|
||||
# --description--
|
||||
|
||||
So far these challenges have avoided discussing asynchronous actions, but they are an unavoidable part of web development. At some point you'll need to call asynchronous endpoints in your Redux app, so how do you handle these types of requests? Redux provides middleware designed specifically for this purpose, called Redux Thunk middleware. Here's a brief description how to use this with Redux.
|
||||
Finora queste sfide hanno evitato di discutere di azioni asincrone, ma esse sono una parte inevitabile dello sviluppo del web. Ad un certo punto dovrai chiamare gli endpoint asincroni nell'app Redux, quindi come gestirai questi tipi di richiesta? Redux fornisce un middleware (software di intermediazione) progettato specificamente per questo scopo, chiamato Redux Thunk middleware. Ecco una breve descrizione di come usarlo con Redux.
|
||||
|
||||
To include Redux Thunk middleware, you pass it as an argument to `Redux.applyMiddleware()`. This statement is then provided as a second optional parameter to the `createStore()` function. Take a look at the code at the bottom of the editor to see this. Then, to create an asynchronous action, you return a function in the action creator that takes `dispatch` as an argument. Within this function, you can dispatch actions and perform asynchronous requests.
|
||||
Per includere il Redux Thunk middleware, lo passi come argomento a `Redux.applyMiddleware()`. Questa istruzione viene quindi fornita come secondo parametro opzionale alla funzione `createStore()`. Dai un'occhiata al codice in fondo all'editor per vederlo. Poi, per creare un'azione asincrona, restituisci una funzione nel creatore di azione che richiede `dispatch` come argomento. All'interno di questa funzione, è possibile inviare azioni ed eseguire richieste asincrone.
|
||||
|
||||
In this example, an asynchronous request is simulated with a `setTimeout()` call. It's common to dispatch an action before initiating any asynchronous behavior so that your application state knows that some data is being requested (this state could display a loading icon, for instance). Then, once you receive the data, you dispatch another action which carries the data as a payload along with information that the action is completed.
|
||||
In questo esempio, una richiesta asincrona viene simulata con una chiamata `setTimeout()`. È comune inviare un'azione prima di iniziare qualsiasi comportamento asincrono in modo che lo stato dell'applicazione sappia che sono stati richiesti alcuni dati (questo stato potrebbe mostrare un'icona di caricamento, per esempio). Poi, una volta ricevuti i dati, si invia un'altra azione che trasporta i dati come payload insieme all'informazione che l'azione è completata.
|
||||
|
||||
Remember that you're passing `dispatch` as a parameter to this special action creator. This is what you'll use to dispatch your actions, you simply pass the action directly to dispatch and the middleware takes care of the rest.
|
||||
Ricorda che stai passando `dispatch` come parametro a questo creatore di azioni speciale. Questo è quello che userai per inviare le tue azioni: passerai l'azione direttamente al dispatch e il middleware si occuperà del resto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write both dispatches in the `handleAsync()` action creator. Dispatch `requestingData()` before the `setTimeout()` (the simulated API call). Then, after you receive the (pretend) data, dispatch the `receivedData()` action, passing in this data. Now you know how to handle asynchronous actions in Redux. Everything else continues to behave as before.
|
||||
Scrivi entrambi i dispatch nel creatore di azioni `handleAsync()`. Fai un dispatch di `requestingData()` prima di `setTimeout()` (la chiamata API simulata). Poi, dopo aver ricevuto i dati (simulati), invia l'azione `receivedData()`, passando questi dati. Ora sai come gestire le azioni asincrone in Redux. Tutto il resto continua a funzionare come prima.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `requestingData` action creator should return an object of type equal to the value of `REQUESTING_DATA`.
|
||||
Il creatore di azione `requestingData` dovrebbe restituire un oggetto type pari al valore di `REQUESTING_DATA`.
|
||||
|
||||
```js
|
||||
assert(requestingData().type === REQUESTING_DATA);
|
||||
```
|
||||
|
||||
The `receivedData` action creator should return an object of type equal to the value of `RECEIVED_DATA`.
|
||||
Il creatore di azione `receivedData` dovrebbe restituire un oggetto type pari al valore di `RECEIVED_DATA`.
|
||||
|
||||
```js
|
||||
assert(receivedData('data').type === RECEIVED_DATA);
|
||||
```
|
||||
|
||||
`asyncDataReducer` should be a function.
|
||||
`asyncDataReducer` dovrebbe essere una funzione.
|
||||
|
||||
```js
|
||||
assert(typeof asyncDataReducer === 'function');
|
||||
```
|
||||
|
||||
Dispatching the `requestingData` action creator should update the store `state` property of fetching to `true`.
|
||||
Il dispatch del creatore di azione `requestingData` dovrebbe aggiornare la proprietà fetching dello `state` dello store a `true`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching `handleAsync` should dispatch the data request action and then dispatch the received data action after a delay.
|
||||
Il dispatch di `handleAsync` dovrebbe inviare l'azione di richiesta di dati e quindi inviare l'azione di ricezione dei dati dopo un certo ritardo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036159
|
||||
title: Use the Spread Operator on Arrays
|
||||
title: Usare l'operatore di propagazione sugli array
|
||||
challengeType: 6
|
||||
forumTopicId: 301452
|
||||
dashedName: use-the-spread-operator-on-arrays
|
||||
@ -8,21 +8,21 @@ dashedName: use-the-spread-operator-on-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
One solution from ES6 to help enforce state immutability in Redux is the spread operator: `...`. The spread operator has a variety of applications, one of which is well-suited to the previous challenge of producing a new array from an existing array. This is relatively new, but commonly used syntax. For example, if you have an array `myArray` and write:
|
||||
Una soluzione di ES6 per contribuire a far rispettare l'immutabilità dello stato in Redux è l'operatore di propagazione (spred): `...`. L'operatore di propagazione ha una varietà di applicazioni, una delle quali si adatta bene alla precedente sfida di produrre un nuovo array da un array esistente. Si tratta di una sintassi relativamente nuova, ma comunemente usata. Ad esempio, se hai un array `myArray` e scrivi:
|
||||
|
||||
```js
|
||||
let newArray = [...myArray];
|
||||
```
|
||||
|
||||
`newArray` is now a clone of `myArray`. Both arrays still exist separately in memory. If you perform a mutation like `newArray.push(5)`, `myArray` doesn't change. The `...` effectively *spreads* out the values in `myArray` into a new array. To clone an array but add additional values in the new array, you could write `[...myArray, 'new value']`. This would return a new array composed of the values in `myArray` and the string `new value` as the last value. The spread syntax can be used multiple times in array composition like this, but it's important to note that it only makes a shallow copy of the array. That is to say, it only provides immutable array operations for one-dimensional arrays.
|
||||
`newArray` è ora un clone di `myArray`. Entrambi gli array esistono ancora separatamente in memoria. Se esegui una mutazione come `newArray.push(5)`, `myArray` non cambia. L'operatore `...` effettivamente *propaga* i valori di `myArray` a un nuovo array. Per clonare un array con dei valori aggiuntivi nel nuovo array, potresti scrivere `[...myArray, 'new value']`. Questo restituirebbe un nuovo array composto dai valori in `myArray` e la stringa `new value` come ultimo valore. La sintassi di propagazione può essere usata più volte in una composizione di array come questa, ma è importante notare che fa solo una copia superficiale dell'array. Vale a dire, fornisce operazioni di array immutabili solo per array unidimensionali.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the spread operator to return a new copy of state when a to-do is added.
|
||||
Usa l'operatore di propagazione per restituire una nuova copia dello stato quando viene aggiunta una cosa da fare.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Redux store should exist and initialize with a state equal to `["Do not mutate state!"]`.
|
||||
Lo store Redux dovrebbe esistere ed essere inizializzato con uno stato uguale a `["Do not mutate state!"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -36,13 +36,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`addToDo` and `immutableReducer` both should be functions.
|
||||
`addToDo` e `immutableReducer` dovrebbero essere entrambe funzioni.
|
||||
|
||||
```js
|
||||
assert(typeof addToDo === 'function' && typeof immutableReducer === 'function');
|
||||
```
|
||||
|
||||
Dispatching an action of type `ADD_TO_DO` on the Redux store should add a `todo` item and should NOT mutate state.
|
||||
L'invio di un'azione di tipo `ADD_TO_DO` allo store di Redux dovrebbe aggiungere un elemento `todo` e NON dovrebbe mutare lo stato.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The spread operator should be used to return new state.
|
||||
L'operatore di propagazione deve essere utilizzato per restituire il nuovo stato.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').includes('...state'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036157
|
||||
title: Write a Counter with Redux
|
||||
title: Scrivere un contatore con Redux
|
||||
challengeType: 6
|
||||
forumTopicId: 301453
|
||||
dashedName: write-a-counter-with-redux
|
||||
@ -8,33 +8,33 @@ dashedName: write-a-counter-with-redux
|
||||
|
||||
# --description--
|
||||
|
||||
Now you've learned all the core principles of Redux! You've seen how to create actions and action creators, create a Redux store, dispatch your actions against the store, and design state updates with pure reducers. You've even seen how to manage complex state with reducer composition and handle asynchronous actions. These examples are simplistic, but these concepts are the core principles of Redux. If you understand them well, you're ready to start building your own Redux app. The next challenges cover some of the details regarding `state` immutability, but first, here's a review of everything you've learned so far.
|
||||
Ora hai imparato tutti i principi fondamentali di Redux! Hai visto come creare azioni e creatori di azioni, creare uno store di Redux, inviare le tue azioni allo store e progettare gli aggiornamenti di stato con i reducer puri. Hai visto anche come gestire uno stato complesso con la composizione di reducer e la gestione di azioni asincrone. Questi esempi sono semplicistici, ma questi concetti sono i principi fondamentali di Redux. Se li capisci bene, sei pronto a iniziare a costruire la tua app con Redux. Le prossime sfide copriranno alcuni dettagli relativi all'immutabilità dello `state`, ma prima, ecco un ripasso di tutto quello che hai imparato finora.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this lesson, you'll implement a simple counter with Redux from scratch. The basics are provided in the code editor, but you'll have to fill in the details! Use the names that are provided and define `incAction` and `decAction` action creators, the `counterReducer()`, `INCREMENT` and `DECREMENT` action types, and finally the Redux `store`. Once you're finished you should be able to dispatch `INCREMENT` or `DECREMENT` actions to increment or decrement the state held in the `store`. Good luck building your first Redux app!
|
||||
In questa lezione, realizzerai da zero un semplice contatore con Redux. Le basi sono fornite nell'editor di codice, ma dovrai riempire i dettagli! Utilizza i nomi forniti e definisci i creatori di azione `incAction` e `decAction`, il reducer `counterReducer()`, i tipi di azione `INCREMENT` e `DECREMENT`, e infine lo `store` di Redux. Una volta terminato, dovresti essere in grado di inviare le azioni `INCREMENT` o `DECREMENT` per aumentare o diminuire lo stato mantenuto nello `store`. Buona fortuna per la costruzione della tua prima app Redux!
|
||||
|
||||
# --hints--
|
||||
|
||||
The action creator `incAction` should return an action object with `type` equal to the value of `INCREMENT`
|
||||
Il creatore di azioni `incAction` dovrebbe restituire un oggetto azione con `type` uguale al valore di `INCREMENT`
|
||||
|
||||
```js
|
||||
assert(incAction().type === INCREMENT);
|
||||
```
|
||||
|
||||
The action creator `decAction` should return an action object with `type` equal to the value of `DECREMENT`
|
||||
Il creatore di azione `decAction` dovrebbe restituire un oggetto azione con `type` uguale al valore di `DECREMENT`
|
||||
|
||||
```js
|
||||
assert(decAction().type === DECREMENT);
|
||||
```
|
||||
|
||||
The Redux store should initialize with a `state` of 0.
|
||||
Lo store Redux dovrebbe essere inizializzato con uno `state` di 0.
|
||||
|
||||
```js
|
||||
assert(store.getState() === 0);
|
||||
```
|
||||
|
||||
Dispatching `incAction` on the Redux store should increment the `state` by 1.
|
||||
Effettuare il dispatch di `incAction` nello store Redux dovrebbe aumentare lo `state` di 1.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dispatching `decAction` on the Redux store should decrement the `state` by 1.
|
||||
Effettuare il dispatch di `decAction` nello store Redux dovrebbe decrementare lo `state` di 1.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -60,7 +60,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`counterReducer` should be a function
|
||||
`counterReducer` dovrebbe essere una funzione
|
||||
|
||||
```js
|
||||
assert(typeof counterReducer === 'function');
|
||||
|
Reference in New Issue
Block a user