diff --git a/src/content/learn/choosing-the-state-structure.md b/src/content/learn/choosing-the-state-structure.md index 5be2b4d34..41300557e 100644 --- a/src/content/learn/choosing-the-state-structure.md +++ b/src/content/learn/choosing-the-state-structure.md @@ -1,53 +1,52 @@ --- -title: Choosing the State Structure +title: Scegliere la struttura dello state --- -Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. Here are some tips you should consider when structuring state. +Strutturare bene lo state può fare la differenza tra un componente piacevole da modificare e debuggare, e uno che sia una costante fonte di bugs. Qui troverai alcuni consigli che dovresti considerare quando strutturi il tuo state -* When to use a single vs multiple state variables -* What to avoid when organizing state -* How to fix common issues with the state structure +* Quando usare una singola vs molteplici variabili di state +* Cosa evitare quando organizzi lo state +* Come correggere problemi comuni strutturando lo state -## Principles for structuring state {/*principles-for-structuring-state*/} +## Principi fondamentali per strutturare lo state {/*principles-for-structuring-state*/} -When you write a component that holds some state, you'll have to make choices about how many state variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal state structure, there are a few principles that can guide you to make better choices: +Quando scrivi un componente che contiene uno state, dovrai fare delle scelte riguardo a quante variabili di state usare e con quali strutture dati lavorare. Benché sia possibile scrivere programmi funzionanti anche con uno state strutturato in maniera suboptimale, ci sono alcuni principi che ti possono guidare nel fare scelte migliori: -1. **Group related state.** If you always update two or more state variables at the same time, consider merging them into a single state variable. -2. **Avoid contradictions in state.** When the state is structured in a way that several pieces of state may contradict and "disagree" with each other, you leave room for mistakes. Try to avoid this. -3. **Avoid redundant state.** If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state. -4. **Avoid duplication in state.** When the same data is duplicated between multiple state variables, or within nested objects, it is difficult to keep them in sync. Reduce duplication when you can. -5. **Avoid deeply nested state.** Deeply hierarchical state is not very convenient to update. When possible, prefer to structure state in a flat way. +1. **Accorpare state in relazione.** Se aggiorni frequentemente due o più variabili di state allo stesso tempo, considera di accorparle all'interno di una singola variabile di state. +2. **Evita contraddizioni nello state.** Quando lo state è strutturato in modo tale che diversi pezzi dello state si possano contraddire e "essere in disaccordo" l'uno con l'altro, lasci spazio a errori. Cerca di evitarlo. +3. **Evita state ridondante.** Se puoi calcolare alcune informazioni dalle props del componente o dalle sue variabili di state esistenti durante il rendering, non dovresti mettere quelle informazioni nello state del componente. +4. **Evita duplicazioni nello state.** Reduce duplication when you can. Quando lo stesso dato è duplicato tra diverse variabili di state, o all'interno di oggetti nidificati, è difficile tenerli sincronizzati. Riduci la duplicazione quando puoi. +5. **Evita state profondamente nidificati** Uno state troppo nidificato non è conveniente da aggiornare. -The goal behind these principles is to *make state easy to update without introducing mistakes*. Removing redundant and duplicate data from state helps ensure that all its pieces stay in sync. This is similar to how a database engineer might want to ["normalize" the database structure](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) to reduce the chance of bugs. To paraphrase Albert Einstein, **"Make your state as simple as it can be--but no simpler."** +L'obbiettivo di questi principi è di *rendere lo state facile da aggiornare senza introdurre errori*. Rimuovere la ridondanza e la duplicazione del dato dallo state aiuta ad essere certi che tutti i suoi pezzi rimangano sincronizzati. Questo è simile a come un database engineer vorrebbe ["normalizzare" la struttura del database](https://docs.microsoft.com/it-it/office/troubleshoot/access/database-normalization-description) per ridurre la probabilità di introdurre bugs. Parafrasando Albert Einstein, **"Rendi il tuo state tanto semplice quanto può esserlo--ma non più semplice"** +Ora vediami questi principi all'azione. -Now let's see how these principles apply in action. +## Accorpare state in relazione {/*group-related-state*/} -## Group related state {/*group-related-state*/} +A volte potresti essere incerto tra usaro una singola o molteplici variabili di state. -You might sometimes be unsure between using a single or multiple state variables. - -Should you do this? +Dovresti fare cosi? ```js const [x, setX] = useState(0); const [y, setY] = useState(0); ``` -Or this? +O cosi? ```js const [position, setPosition] = useState({ x: 0, y: 0 }); ``` -Technically, you can use either of these approaches. But **if some two state variables always change together, it might be a good idea to unify them into a single state variable.** Then you won't forget to always keep them in sync, like in this example where moving the cursor updates both coordinates of the red dot: +Tecnicamente, puoi usare entrambi gli approcci. Ma **se due variabili dello state cambiano sempre insieme, potrebbe essere una buona idea accorparle in una singola variabile di state.** In questo modo non dimenticherai di tenerle sempre sincronizzate, come in questo esempio dove muovere il cursore aggiorna entrambe le coordinate del punto rosso: @@ -93,18 +92,20 @@ body { margin: 0; padding: 0; height: 250px; } -Another case where you'll group data into an object or an array is when you don't know how many pieces of state you'll need. For example, it's helpful when you have a form where the user can add custom fields. +Un altro caso in qui accorperai dati in un oggetti o in un array è quando non sai di quanti pezzi di state avrai bisogno. Per esempio, è utile quando hai un form dove l'utente può aggiungere campi personalizzati. -If your state variable is an object, remember that [you can't update only one field in it](/learn/updating-objects-in-state) without explicitly copying the other fields. For example, you can't do `setPosition({ x: 100 })` in the above example because it would not have the `y` property at all! Instead, if you wanted to set `x` alone, you would either do `setPosition({ ...position, x: 100 })`, or split them into two state variables and do `setX(100)`. +Se la tua variabile di state è un oggetto, ricorda che [non puoi aggiornarne solo un campo](/learn/updating-objects-in-state) senza esplicitamente copiare gli altri campi. Per esempio, non puoi fare `setPosition({ x: 100 })` nell'esempio sopra perché non avrebbe la proprietà `y`! Invece, se vuoi impostare solamente `x`, dovresti fare `setPosition({ ...position, x: 100 })`, or dividendoli in due variabili di state e fare `setX(100)`. -## Avoid contradictions in state {/*avoid-contradictions-in-state*/} +## Evita contraddizioni nello state {/*avoid-contradictions-in-state*/} Here is a hotel feedback form with `isSending` and `isSent` state variables: +Questo è il feedback form di un hotel con le variabili di state `isSending` e `isSent` + ```js @@ -157,9 +158,10 @@ function sendMessage(text) { -While this code works, it leaves the door open for "impossible" states. For example, if you forget to call `setIsSent` and `setIsSending` together, you may end up in a situation where both `isSending` and `isSent` are `true` at the same time. The more complex your component is, the harder it is to understand what happened. +Anche se questo codice funziona, lascia spazio a state "impossibili". Per esempio, se dimentichi di chiamare `setIsSent` e `setIsSending` insieme, potresti incappare in una situazione dove entrambi `isSending` e `isSent` sono `true` allo stesso tempo. Più complesso è il tuo componente, più difficile è capire cos'è successo, **Since `isSending` and `isSent` should never be `true` at the same time, it is better to replace them with one `status` state variable that may take one of *three* valid states:** `'typing'` (initial), `'sending'`, and `'sent'`: +**Poiché `isSending` e `isSent` non dovrebbero mai essere `true` allo stesso tempo, è meglio rimpiazzarli con una singola variabile di state `status` che possa prendere uno dei *tre* state validi: `'typing'` (iniziale), `'sending'`, e `'sent'`:** @@ -214,20 +216,20 @@ function sendMessage(text) { -You can still declare some constants for readability: +Puoi anche dichiarare alcune costanti per aumentare la leggibilità: ```js const isSending = status === 'sending'; const isSent = status === 'sent'; ``` -But they're not state variables, so you don't need to worry about them getting out of sync with each other. +Ma non sono variabili dello state, quindi non devi preoccuparti di tenerle sincronizzate. -## Avoid redundant state {/*avoid-redundant-state*/} +## Evita state ridondante {/*avoid-redundant-state*/} -If you can calculate some information from the component's props or its existing state variables during rendering, you **should not** put that information into that component's state. +Se puoi calcolare alcune informazioni dalle props del componente o dalle sue variabili di state esistenti durante il rendering, non **dovresti** mettere quell'informazione nello state del componente. -For example, take this form. It works, but can you find any redundant state in it? +Ad esempio, prendi questo form. Funziona, ma riesci a trovare qualche state ridondante? @@ -280,9 +282,9 @@ label { display: block; margin-bottom: 5px; } -This form has three state variables: `firstName`, `lastName`, and `fullName`. However, `fullName` is redundant. **You can always calculate `fullName` from `firstName` and `lastName` during render, so remove it from state.** +Questo form ha tre variabili nel suo state: `firstName`, `lastName`, e `fullName`. Ma `fullName` è ridondante. **Puoi sempre calcolare `fullName` da `firstName` e `lastName` durante il render, quindi rimuovilo dallo state.** -This is how you can do it: +Questo è come puoi farlo: @@ -334,37 +336,36 @@ label { display: block; margin-bottom: 5px; } -Here, `fullName` is *not* a state variable. Instead, it's calculated during render: +Qui, `fullName` *non* è una variabile dello state, è calcolata durante il render ```js const fullName = firstName + ' ' + lastName; ``` -As a result, the change handlers don't need to do anything special to update it. When you call `setFirstName` or `setLastName`, you trigger a re-render, and then the next `fullName` will be calculated from the fresh data. +Come risultato, gli handlers non devono fare niente di speciale per aggiornarlo. Quando chiami `setFirstName` o `setLastName`, attivi un nuovo rendering, e quindi il nuovo `fullName` sarà calcolato a partire dai dati aggiornati. -#### Don't mirror props in state {/*don-t-mirror-props-in-state*/} +#### Non specchiare le props nello state {/*don-t-mirror-props-in-state*/} -A common example of redundant state is code like this: +Un esempio comune di state ridondante è: ```js function Message({ messageColor }) { - const [color, setColor] = useState(messageColor); + const [color, setColor] = useState(messageColor) ``` -Here, a `color` state variable is initialized to the `messageColor` prop. The problem is that **if the parent component passes a different value of `messageColor` later (for example, `'red'` instead of `'blue'`), the `color` *state variable* would not be updated!** The state is only initialized during the first render. +Qui la variabile di state `color` è inizializzata con la prop `messageColor`. Il problema è che **se il componente genitore passasse, in un secondo momento, un valore diverso di `messageColor`(per esempio, `'red'` invece di `'blue'`), la *variabile di state* `color` non verrebbe aggiornata!* Lo state è inzializzato solo durante il primo render. -This is why "mirroring" some prop in a state variable can lead to confusion. Instead, use the `messageColor` prop directly in your code. If you want to give it a shorter name, use a constant: +Questo è il motivo per cui "specchiare" alcune prop in una variabile di state può portare a confusione. Invece, usa la prop `messageColor` direttamente nel tuo codice. Se vuoi darle un nome più corto usa una costante: ```js function Message({ messageColor }) { const color = messageColor; ``` +In questo modo si manterrà sincronizzata con la prop passata dal componente genitore. -This way it won't get out of sync with the prop passed from the parent component. - -"Mirroring" props into state only makes sense when you *want* to ignore all updates for a specific prop. By convention, start the prop name with `initial` or `default` to clarify that its new values are ignored: +"Specchiare" le props nello state ha senso solo quando *vuoi* ignorare tutti gli aggiornamenti di una specifica prop. Per convenzione, inizia il nome della prop con `initial` o `default` per chiarire che i suoi nuovi valore sono ignorati: ```js function Message({ initialColor }) { @@ -375,9 +376,9 @@ function Message({ initialColor }) { -## Avoid duplication in state {/*avoid-duplication-in-state*/} +## Evita duplicazioni nello state {/*avoid-duplication-in-state*/} -This menu list component lets you choose a single travel snack out of several: +Questo componente menu ti permette di scegliere un singolo snack tra quelli disponibili: @@ -422,9 +423,9 @@ button { margin-top: 10px; } -Currently, it stores the selected item as an object in the `selectedItem` state variable. However, this is not great: **the contents of the `selectedItem` is the same object as one of the items inside the `items` list.** This means that the information about the item itself is duplicated in two places. +Attualmente, memorizza l'item selezionato come un oggetto nell variabile di state `selectedItem`. Non è ideale: **`items` contiene un oggetto tra quelli contenuti nella lista di `selectedItem`.** Questo significa che l'informazione riguardante l'item stesso è duplicata in due posti. -Why is this a problem? Let's make each item editable: +Perché è un problema? Rendiamo ogni item editabile: @@ -487,9 +488,9 @@ button { margin-top: 10px; } -Notice how if you first click "Choose" on an item and *then* edit it, **the input updates but the label at the bottom does not reflect the edits.** This is because you have duplicated state, and you forgot to update `selectedItem`. +Hai notato che se clicchi "Choose" su un item a *poi* lo modifichi, **l'input si aggiorna ma la label in fondo non riflette le modifiche.** Questo perché hai lo state duplicato, e hai dimenticato di aggiornare `selectedItem`. -Although you could update `selectedItem` too, an easier fix is to remove duplication. In this example, instead of a `selectedItem` object (which creates a duplication with objects inside `items`), you hold the `selectedId` in state, and *then* get the `selectedItem` by searching the `items` array for an item with that ID: +Sebbene tu possa aggiornare anche `selectedItem`, rimuovere la duplicazione è un fix più semplice. In questo esempio, invece di un oggetto `selectedItem` (che crea una duplicazione con gli oggetti dentro `items`), tieni il `selectedId` nello state, e *poi* prendi il `selectedItem` cercando nell'array `items` l'item con quell'ID: @@ -554,23 +555,22 @@ button { margin-top: 10px; } -The state used to be duplicated like this: +Lo state era duplicato in questo modo: * `items = [{ id: 0, title: 'pretzels'}, ...]` * `selectedItem = {id: 0, title: 'pretzels'}` -But after the change it's like this: +Ma dopo le modifiche è cosi: * `items = [{ id: 0, title: 'pretzels'}, ...]` * `selectedId = 0` -The duplication is gone, and you only keep the essential state! - -Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in state, because only the *selected ID* is essential. The rest could be calculated during render. +La duplicazione è stata rimossa, e mantieni solo lo state essenziale! -## Avoid deeply nested state {/*avoid-deeply-nested-state*/} +Ora se modifichi il *selected* item, il messaggio sotto si aggiornerà immediatamente. Questo perché `setItems` aziona un nuovo render, e `items.find(...)` trova l'item con il titolo aggiornato. Non avevi bisogno ti tenere *l'item selezionato* nello state, perché solo il *selected ID* è essenziale. Il resto può essere calcolato durante il render. +## Evita state profondamente nidificati {/*avoid-deeply-nested-state*/} -Imagine a travel plan consisting of planets, continents, and countries. You might be tempted to structure its state using nested objects and arrays, like in this example: +Immagina un piano di viaggio che comprende pianeti, continenti e paesi. Potresti essere tentato di strutturare il suo state usando oggetti e array nidificati, come in questo esempio: @@ -812,11 +812,11 @@ export const initialTravelPlan = { -Now let's say you want to add a button to delete a place you've already visited. How would you go about it? [Updating nested state](/learn/updating-objects-in-state#updating-a-nested-object) involves making copies of objects all the way up from the part that changed. Deleting a deeply nested place would involve copying its entire parent place chain. Such code can be very verbose. +Ora diciamo che tu voglia aggiungere un bottone per cancellare un luogo che hai già visitato. Come procederesti? [Aggiornare state nidificati](/learn/updating-objects-in-state#updating-a-nested-object) implica fare copie degli oggetti fino alla parte che è cambiata. Cancellare un luogo che si trova in una posizione profonda implicherebbe copiare la sua intera catena di genitori. Un codice del genere può essere molto verboso. -**If the state is too nested to update easily, consider making it "flat".** Here is one way you can restructure this data. Instead of a tree-like structure where each `place` has an array of *its child places*, you can have each place hold an array of *its child place IDs*. Then store a mapping from each place ID to the corresponding place. +**Se lo state è troppo nidificato per essere aggiornato facilmente, considera di renderlo "flat".** Qui trovi un modo per ristrutturare questi dati. Invece di una struttura ad albero dove ogni `place` ha un array di *suoi place figli*, puoi fare in modo che ogni place contenga un array di *IDs di suoi place figli*. Poi salvare un mapping che metta in correlazione ogni place ID al suo place corrispondente. -This data restructuring might remind you of seeing a database table: +Questa ristrutturazione dei dati potrebbe ricordarti la tabella di un database: @@ -1118,14 +1118,14 @@ export const initialTravelPlan = { -**Now that the state is "flat" (also known as "normalized"), updating nested items becomes easier.** +**Ora che lo state è "piatto" (anche detto "normalizzato"), aggiornare gli elementi nidificati diventa più facile.** -In order to remove a place now, you only need to update two levels of state: +Adesso per rimuovere un place devi solo aggiornare due livelli dello state: -- The updated version of its *parent* place should exclude the removed ID from its `childIds` array. -- The updated version of the root "table" object should include the updated version of the parent place. +- La versione aggiornata del place *genitore* dovrebbe escludere l'ID rimosso dal suo array `childIds`. +- La versione aggiornata dell'oggetto root dovrebbe includere la versione aggiornata del place genitore. -Here is an example of how you could go about it: +Qui un esempio di come potresti farlo: @@ -1458,13 +1458,13 @@ button { margin: 10px; } -You can nest state as much as you like, but making it "flat" can solve numerous problems. It makes state easier to update, and it helps ensure you don't have duplication in different parts of a nested object. +Non c'è limite a quanto profondamente puoi annidare lo state, ma farlo "flat" può risolvere numerosi problemi. Rende lo state più facile da aggiornare, e ti aiuta ad assicurarti di non avere duplicazioni nelle diverse parti di un oggetto nidificato. -#### Improving memory usage {/*improving-memory-usage*/} +#### Migliora l'utilizzo della memoria {/*improving-memory-usage*/} -Ideally, you would also remove the deleted items (and their children!) from the "table" object to improve memory usage. This version does that. It also [uses Immer](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) to make the update logic more concise. +Idealmente, potresti rimuovere gli items eliminati (e il loro figli!) dall'oggetto "table" per migliorare l'utilizzo della memoria. Questa versione lo fa. Inoltre [usa Immer](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) per rendere la logica di aggiornamento dello state più concisa. @@ -1817,25 +1817,25 @@ button { margin: 10px; } -Sometimes, you can also reduce state nesting by moving some of the nested state into the child components. This works well for ephemeral UI state that doesn't need to be stored, like whether an item is hovered. +Talvolta potrai anche ridurre la nidificazione dello state spostando parte dello state nidificato nei componenti figlio. Questo funziona bene per gli state effimeri dell'interfaccia utente che non hanno bisogno di essere memorizzati. Come ad esempio se un elemento è stato selezionato con il mouse. -* If two state variables always update together, consider merging them into one. -* Choose your state variables carefully to avoid creating "impossible" states. -* Structure your state in a way that reduces the chances that you'll make a mistake updating it. -* Avoid redundant and duplicate state so that you don't need to keep it in sync. -* Don't put props *into* state unless you specifically want to prevent updates. -* For UI patterns like selection, keep ID or index in state instead of the object itself. -* If updating deeply nested state is complicated, try flattening it. +* Se due variabili di state vengono sempre aggiornate insieme, valuta la possibilità di unirle in una sola. +* Scegli con attenzione le variabili di state per evitare di creare stati “impossibili”. +* Struttura lo state in modo da ridurre le possibilità di commettere errori durante l'aggiornamento. +* Evita state ridondanti e duplicati in modo da non doverli mantenere sincronizzati. +* Non inserire props *nello* state a meno che non si voglia specificatamente impedire gli aggiornamenti. +* Nei pattern di interfaccia utente come la selezione, mantieni l'ID o l'indice nello state invece dell'oggetto stesso. +* Se l'aggiornamento di uno state profondamente annidato è complicato, prova ad appiattirlo. -#### Fix a component that's not updating {/*fix-a-component-thats-not-updating*/} +#### Correggi un componente che non si sta aggiornando {/*fix-a-component-thats-not-updating*/} -This `Clock` component receives two props: `color` and `time`. When you select a different color in the select box, the `Clock` component receives a different `color` prop from its parent component. However, for some reason, the displayed color doesn't update. Why? Fix the problem. +Questo componente `Clock` riceve due proprietà: `color` e `time`. Quando selezioni un colore diverso nella casella di selezione, il componente `Clock` riceve una proprietà `color` diversa dal suo componente padre. Tuttavia, per qualche motivo, il colore visualizzato non viene aggiornato. Perché? Risolvi il problema. @@ -1890,7 +1890,7 @@ export default function App() { -The issue is that this component has `color` state initialized with the initial value of the `color` prop. But when the `color` prop changes, this does not affect the state variable! So they get out of sync. To fix this issue, remove the state variable altogether, and use the `color` prop directly. +Il problema è che questo componente ha lo state `color` inizializzato con il valore iniziale della proprietà `color`. Ma quando la proprietà `color` cambia, ciò non influisce sulla variabile di state! Quindi non sono più sincronizzati. Per risolvere questo problema, rimuovi completamente la variabile di state e utilizza direttamente la proprietà `color`. @@ -1942,7 +1942,7 @@ export default function App() { -Or, using the destructuring syntax: +O, utilizza la sintassi di destructuring: @@ -1998,11 +1998,11 @@ export default function App() { #### Fix a broken packing list {/*fix-a-broken-packing-list*/} -This packing list has a footer that shows how many items are packed, and how many items there are overall. It seems to work at first, but it is buggy. For example, if you mark an item as packed and then delete it, the counter will not be updated correctly. Fix the counter so that it's always correct. +Questa lista di imballaggio ha un piè di pagina che mostra quanti articoli sono stati imballati e quanti articoli ci sono in totale. All'inizio sembra funzionare, ma presenta dei bug. Ad esempio, se si contrassegna un articolo come imballato e poi lo si elimina, il contatore non viene aggiornato correttamente. Correggere il contatore in modo che sia sempre corretto. -Is any state in this example redundant? +C'è uno state ridondante in questo esempio? @@ -2143,7 +2143,7 @@ ul, li { margin: 0; padding: 0; } -Although you could carefully change each event handler to update the `total` and `packed` counters correctly, the root problem is that these state variables exist at all. They are redundant because you can always calculate the number of items (packed or total) from the `items` array itself. Remove the redundant state to fix the bug: +Sebbene sia possibile modificare con attenzione ogni gestore di eventi per aggiornare correttamente i contatori `total` e `packed`, il problema principale è che queste variabili di state esistono. Sono ridondanti perché è sempre possibile calcolare il numero di elementi (imballati o totali) dall'array `items` stesso. Rimuovere lo state ridondante per correggere il bug: @@ -2276,15 +2276,15 @@ ul, li { margin: 0; padding: 0; } -Notice how the event handlers are only concerned with calling `setItems` after this change. The item counts are now calculated during the next render from `items`, so they are always up-to-date. +Si noti come gli handler degli eventi si occupino solo di chiamare `setItems` dopo questa modifica. Il conteggio degli elementi viene ora calcolato durante il rendering successivo da `items`, quindi è sempre aggiornato. -#### Fix the disappearing selection {/*fix-the-disappearing-selection*/} +#### Correggi la scomparsa della selezione {/*fix-the-disappearing-selection*/} -There is a list of `letters` in state. When you hover or focus a particular letter, it gets highlighted. The currently highlighted letter is stored in the `highlightedLetter` state variable. You can "star" and "unstar" individual letters, which updates the `letters` array in state. +C'è un elenco di `lettere` nello state. Quando si passa il mouse o si seleziona una lettera particolare, questa viene evidenziata. La lettera attualmente evidenziata viene memorizzata nella variabile di state `highlightedLetter`. È possibile “contrassegnare” e “rimuovere il contrassegno” delle singole lettere, aggiornando così l'array `letters` nello state. -This code works, but there is a minor UI glitch. When you press "Star" or "Unstar", the highlighting disappears for a moment. However, it reappears as soon as you move your pointer or switch to another letter with keyboard. Why is this happening? Fix it so that the highlighting doesn't disappear after the button click. +Questo codice funziona, ma c'è un piccolo problema nell'interfaccia utente. Quando si preme “Contrassegna” o “Rimuovi contrassegno”, l'evidenziazione scompare per un istante. Tuttavia, riappare non appena si sposta il puntatore o si passa a un'altra lettera con la tastiera. Perché succede questo? Correggere il codice in modo che l'evidenziazione non scompaia dopo aver cliccato sul pulsante. @@ -2391,9 +2391,9 @@ li { border-radius: 5px; } -The problem is that you're holding the letter object in `highlightedLetter`. But you're also holding the same information in the `letters` array. So your state has duplication! When you update the `letters` array after the button click, you create a new letter object which is different from `highlightedLetter`. This is why `highlightedLetter === letter` check becomes `false`, and the highlight disappears. It reappears the next time you call `setHighlightedLetter` when the pointer moves. +Il problema è che stai conservando l'oggetto letter in `highlightedLetter`. Ma stai conservando le stesse informazioni anche nell'array `letters`. Quindi il tuo state presenta una duplicazione! Quando aggiorni l'array `letters` dopo aver cliccato sul pulsante, crei un nuovo oggetto lettera che è diverso da `highlightedLetter`. Questo è il motivo per cui il controllo `highlightedLetter === letter` diventa `false` e l'evidenziazione scompare. Riappare la volta successiva che chiami `setHighlightedLetter` quando il puntatore si sposta. -To fix the issue, remove the duplication from state. Instead of storing *the letter itself* in two places, store the `highlightedId` instead. Then you can check `isHighlighted` for each letter with `letter.id === highlightedId`, which will work even if the `letter` object has changed since the last render. +Per risolvere il problema, rimuovi la duplicazione dallo state. Invece di memorizzare *la lettera stessa* in due posti, memorizza invece `highlightedId`. Quindi puoi controllare `isHighlighted` per ogni lettera con `letter.id === highlightedId`, che funzionerà anche se l'oggetto `letter` è cambiato dall'ultimo rendering. @@ -2500,15 +2500,15 @@ li { border-radius: 5px; } -#### Implement multiple selection {/*implement-multiple-selection*/} +#### Implementa selezioni multiple {/*implement-multiple-selection*/} -In this example, each `Letter` has an `isSelected` prop and an `onToggle` handler that marks it as selected. This works, but the state is stored as a `selectedId` (either `null` or an ID), so only one letter can get selected at any given time. +In questo esempio, ogni `Letter` ha una proprietà `isSelected` e un gestore `onToggle` che la contrassegna come selezionata. Questo funziona, ma lo state viene memorizzato come `selectedId` (`null` o un ID), quindi è possibile selezionare solo una lettera alla volta. -Change the state structure to support multiple selection. (How would you structure it? Think about this before writing the code.) Each checkbox should become independent from the others. Clicking a selected letter should uncheck it. Finally, the footer should show the correct number of the selected items. +Modifica la struttura dello state per supportare la selezione multipla. (Come la struttureresti? Pensaci prima di scrivere il codice.) Ogni casella di controllo dovrebbe diventare indipendente dalle altre. Cliccando su una lettera selezionata, questa dovrebbe deselezionarsi. Infine, il piè di pagina dovrebbe mostrare il numero corretto di elementi selezionati. -Instead of a single selected ID, you might want to hold an array or a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) of selected IDs in state. +Invece di un singolo ID selezionato, potresti voler conservare un array o un [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) di ID selezionati nello state. @@ -2609,7 +2609,7 @@ label { width: 100%; padding: 5px; display: inline-block; } -Instead of a single `selectedId`, keep a `selectedIds` *array* in state. For example, if you select the first and the last letter, it would contain `[0, 2]`. When nothing is selected, it would be an empty `[]` array: +Invece di un singolo `selectedId`, mantieni uno `array` `selectedIds` nello state. Ad esempio, se selezioni la prima e l'ultima lettera, conterrà `[0, 2]`. Quando non è selezionato nulla, sarà un array vuoto `[]`: @@ -2715,9 +2715,9 @@ label { width: 100%; padding: 5px; display: inline-block; } -One minor downside of using an array is that for each item, you're calling `selectedIds.includes(letter.id)` to check whether it's selected. If the array is very large, this can become a performance problem because array search with [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) takes linear time, and you're doing this search for each individual item. +Uno svantaggio minore dell'utilizzo di un array è che per ogni elemento è necessario chiamare `selectedIds.includes(letter.id)` per verificare se è selezionato. Se l'array è molto grande, questo può diventare un problema di prestazioni perché la ricerca nell'array con [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) richiede un tempo lineare e questa ricerca viene eseguita per ogni singolo elemento. -To fix this, you can hold a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) in state instead, which provides a fast [`has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has) operation: +Per risolvere questo problema, puoi invece mantenere un [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) nello stato, che fornisce una veloce operazione [`has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has): @@ -2820,9 +2820,9 @@ label { width: 100%; padding: 5px; display: inline-block; } -Now each item does a `selectedIds.has(letter.id)` check, which is very fast. +Ora ogni elemento esegue un controllo `selectedIds.has(letter.id)`, che è molto veloce. -Keep in mind that you [should not mutate objects in state](/learn/updating-objects-in-state), and that includes Sets, too. This is why the `handleToggle` function creates a *copy* of the Set first, and then updates that copy. +Tieni presente che [non dovresti modificare gli oggetti nello stato](/learn/updating-objects-in-state), e questo include anche i Set. Questo è il motivo per cui la funzione `handleToggle` crea prima una *copia* del Set e poi aggiorna quella copia. diff --git a/src/sidebarLearn.json b/src/sidebarLearn.json index 2d6388f93..4fc8ac56b 100644 --- a/src/sidebarLearn.json +++ b/src/sidebarLearn.json @@ -153,7 +153,7 @@ "path": "/learn/reacting-to-input-with-state" }, { - "title": "Choosing the State Structure", + "title": "Scegliere la struttura dello state", "path": "/learn/choosing-the-state-structure" }, {