diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md
index 685f63ef4..88ca00e57 100644
--- a/src/content/learn/preserving-and-resetting-state.md
+++ b/src/content/learn/preserving-and-resetting-state.md
@@ -1,28 +1,35 @@
---
-title: Preserving and Resetting State
+title: Preservare e Reimpostare lo State
+translationStatus: ai-draft
---
+
+
+Questa pagina è stata tradotta automaticamente e supervisionata da un maintainer. Un'ulteriore revisione da parte della community sarebbe comunque utile. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/learn/preserving-and-resetting-state.md).
+
+
+
-State is isolated between components. React keeps track of which state belongs to which component based on their place in the UI tree. You can control when to preserve state and when to reset it between re-renders.
+Lo state è isolato tra i componenti. React tiene traccia di quale state appartiene a quale componente in base alla sua posizione nell'albero dell'UI. Puoi controllare quando preservare lo state e quando reimpostarlo tra le ri-renderizzazioni.
-* When React chooses to preserve or reset the state
-* How to force React to reset component's state
-* How keys and types affect whether the state is preserved
+* Quando React sceglie di preservare o reimpostare lo state
+* Come forzare React a reimpostare lo state di un componente
+* Come le key e i tipi influenzano se lo state viene preservato
-## State is tied to a position in the render tree {/*state-is-tied-to-a-position-in-the-tree*/}
+## Lo state è legato a una posizione nell'albero di renderizzazione {/*state-is-tied-to-a-position-in-the-tree*/}
-React builds [render trees](learn/understanding-your-ui-as-a-tree#the-render-tree) for the component structure in your UI.
+React costruisce [alberi di renderizzazione](/learn/understanding-your-ui-as-a-tree#the-render-tree) per la struttura dei componenti nella tua UI.
-When you give a component state, you might think the state "lives" inside the component. But the state is actually held inside React. React associates each piece of state it's holding with the correct component by where that component sits in the render tree.
+Quando dai state a un componente, potresti pensare che lo state "viva" dentro il componente. Ma lo state è in realtà conservato dentro React. React associa ogni pezzo di state che conserva al componente corretto in base a dove quel componente si trova nell'albero di renderizzazione.
-Here, there is only one `` JSX tag, but it's rendered at two different positions:
+Qui c'è un solo tag JSX ``, ma viene renderizzato in due posizioni diverse:
@@ -56,7 +63,7 @@ function Counter() {
>
{score}
);
@@ -86,23 +93,23 @@ label {
-Here's how these look as a tree:
+Ecco come appaiono come albero:
-
+
-React tree
+Albero React
-**These are two separate counters because each is rendered at its own position in the tree.** You don't usually have to think about these positions to use React, but it can be useful to understand how it works.
+**Questi sono due contatori separati perché ciascuno è renderizzato nella propria posizione nell'albero.** Di solito non devi pensare a queste posizioni per usare React, ma può essere utile capire come funziona.
-In React, each component on the screen has fully isolated state. For example, if you render two `Counter` components side by side, each of them will get its own, independent, `score` and `hover` states.
+In React, ogni componente sullo schermo ha uno state completamente isolato. Ad esempio, se renderizzi due componenti `Counter` affiancati, ciascuno avrà i propri state `score` e `hover` indipendenti.
-Try clicking both counters and notice they don't affect each other:
+Prova a cliccare entrambi i contatori e nota che non si influenzano a vicenda:
@@ -135,7 +142,7 @@ function Counter() {
>
{score}
);
@@ -160,21 +167,21 @@ function Counter() {
-As you can see, when one counter is updated, only the state for that component is updated:
+Come puoi vedere, quando un contatore viene aggiornato, viene aggiornato solo lo state di quel componente:
-
+
-Updating state
+Aggiornamento dello state
-React will keep the state around for as long as you render the same component at the same position in the tree. To see this, increment both counters, then remove the second component by unchecking "Render the second counter" checkbox, and then add it back by ticking it again:
+React manterrà lo state finché renderizzi lo stesso componente nella stessa posizione nell'albero. Per vederlo, incrementa entrambi i contatori, poi rimuovi il secondo componente deselezionando la checkbox "Renderizza il secondo contatore", e aggiungilo di nuovo selezionandola:
@@ -195,7 +202,7 @@ export default function App() {
setShowB(e.target.checked)
}}
/>
- Render the second counter
+ Renderizza il secondo contatore
);
@@ -218,7 +225,7 @@ function Counter() {
>
{score}
);
@@ -248,35 +255,35 @@ label {
-Notice how the moment you stop rendering the second counter, its state disappears completely. That's because when React removes a component, it destroys its state.
+Nota come nel momento in cui smetti di renderizzare il secondo contatore, il suo state scompare completamente. Questo perché quando React rimuove un componente, ne distrugge lo state.
-
+
-Deleting a component
+Eliminazione di un componente
-When you tick "Render the second counter", a second `Counter` and its state are initialized from scratch (`score = 0`) and added to the DOM.
+Quando selezioni "Renderizza il secondo contatore", un secondo `Counter` e il suo state vengono inizializzati da zero (`score = 0`) e aggiunti al DOM.
-
+
-Adding a component
+Aggiunta di un componente
-**React preserves a component's state for as long as it's being rendered at its position in the UI tree.** If it gets removed, or a different component gets rendered at the same position, React discards its state.
+**React preserva lo state di un componente finché viene renderizzato nella sua posizione nell'albero dell'UI.** Se viene rimosso, o se un componente diverso viene renderizzato nella stessa posizione, React scarta il suo state.
-## Same component at the same position preserves state {/*same-component-at-the-same-position-preserves-state*/}
+## Lo stesso componente nella stessa posizione preserva lo state {/*same-component-at-the-same-position-preserves-state*/}
-In this example, there are two different `` tags:
+In questo esempio, ci sono due tag `` diversi:
@@ -300,7 +307,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ Usa stile elegante
);
@@ -326,7 +333,7 @@ function Counter({ isFancy }) {
>
{score}
);
@@ -361,24 +368,24 @@ label {
-When you tick or clear the checkbox, the counter state does not get reset. Whether `isFancy` is `true` or `false`, you always have a `` as the first child of the `div` returned from the root `App` component:
+Quando selezioni o deselezioni la checkbox, lo state del contatore non viene reimpostato. Che `isFancy` sia `true` o `false`, hai sempre un `` come primo figlio del `div` restituito dal componente root `App`:
-
+
-Updating the `App` state does not reset the `Counter` because `Counter` stays in the same position
+Aggiornare lo state di `App` non reimposta `Counter` perché `Counter` resta nella stessa posizione
-It's the same component at the same position, so from React's perspective, it's the same counter.
+È lo stesso componente nella stessa posizione, quindi dal punto di vista di React, è lo stesso contatore.
-Remember that **it's the position in the UI tree--not in the JSX markup--that matters to React!** This component has two `return` clauses with different `` JSX tags inside and outside the `if`:
+Ricorda che **è la posizione nell'albero dell'UI — non nel markup JSX — che conta per React!** Questo componente ha due clausole `return` con tag JSX `` diversi dentro e fuori l'`if`:
@@ -399,7 +406,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ Usa stile elegante
);
@@ -415,7 +422,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ Usa stile elegante
);
@@ -441,7 +448,7 @@ function Counter({ isFancy }) {
>
{score}
);
@@ -476,15 +483,15 @@ label {
-You might expect the state to reset when you tick checkbox, but it doesn't! This is because **both of these `` tags are rendered at the same position.** React doesn't know where you place the conditions in your function. All it "sees" is the tree you return.
+Potresti aspettarti che lo state venga reimpostato quando selezioni la checkbox, ma non succede! Questo perché **entrambi questi tag `` sono renderizzati nella stessa posizione.** React non sa dove posizioni le condizioni nella tua funzione. Tutto ciò che "vede" è l'albero che restituisci.
-In both cases, the `App` component returns a `
` with `` as a first child. To React, these two counters have the same "address": the first child of the first child of the root. This is how React matches them up between the previous and next renders, regardless of how you structure your logic.
+In entrambi i casi, il componente `App` restituisce un `
` con `` come primo figlio. Per React, questi due contatori hanno lo stesso "indirizzo": il primo figlio del primo figlio della root. È così che React li abbina tra la renderizzazione precedente e quella successiva, indipendentemente da come strutturi la tua logica.
-## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/}
+## Componenti diversi nella stessa posizione reimpostano lo state {/*different-components-at-the-same-position-reset-state*/}
-In this example, ticking the checkbox will replace `` with a `
`:
+In questo esempio, selezionare la checkbox sostituirà `` con un `
) : (
)}
@@ -508,7 +515,7 @@ export default function App() {
setIsPaused(e.target.checked)
}}
/>
- Take a break
+ Fai una pausa
);
@@ -531,7 +538,7 @@ function Counter() {
>
{score}
);
@@ -561,13 +568,13 @@ label {
-Here, you switch between _different_ component types at the same position. Initially, the first child of the `
` contained a `Counter`. But when you swapped in a `p`, React removed the `Counter` from the UI tree and destroyed its state.
+Qui, passi tra tipi di componente _diversi_ nella stessa posizione. Inizialmente, il primo figlio del `
` conteneva un `Counter`. Ma quando lo hai sostituito con un `p`, React ha rimosso il `Counter` dall'albero dell'UI e ha distrutto il suo state.
-
+
-When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added
+Quando `Counter` diventa `p`, il `Counter` viene eliminato e il `p` viene aggiunto
@@ -575,15 +582,15 @@ When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added
-
+
-When switching back, the `p` is deleted and the `Counter` is added
+Quando si torna indietro, il `p` viene eliminato e il `Counter` viene aggiunto
-Also, **when you render a different component in the same position, it resets the state of its entire subtree.** To see how this works, increment the counter and then tick the checkbox:
+Inoltre, **quando renderizzi un componente diverso nella stessa posizione, reimposta lo state dell'intero sottoalbero.** Per vedere come funziona, incrementa il contatore e poi seleziona la checkbox:
@@ -611,7 +618,7 @@ export default function App() {
setIsFancy(e.target.checked)
}}
/>
- Use fancy styling
+ Usa stile elegante
);
@@ -672,13 +679,13 @@ label {
-The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `section` to a `div`. When the child `section` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
+Lo state del contatore viene reimpostato quando clicchi la checkbox. Anche se renderizzi un `Counter`, il primo figlio del `div` cambia da un `section` a un `div`. Quando il figlio `section` è stato rimosso dal DOM, l'intero albero sotto di esso (inclusi il `Counter` e il suo state) è stato distrutto.
-
+
-When `section` changes to `div`, the `section` is deleted and the new `div` is added
+Quando `section` diventa `div`, il `section` viene eliminato e il nuovo `div` viene aggiunto
@@ -686,21 +693,21 @@ When `section` changes to `div`, the `section` is deleted and the new `div` is a
-
+
-When switching back, the `div` is deleted and the new `section` is added
+Quando si torna indietro, il `div` viene eliminato e il nuovo `section` viene aggiunto
-As a rule of thumb, **if you want to preserve the state between re-renders, the structure of your tree needs to "match up"** from one render to another. If the structure is different, the state gets destroyed because React destroys state when it removes a component from the tree.
+Come regola generale, **se vuoi preservare lo state tra le ri-renderizzazioni, la struttura del tuo albero deve "corrispondere"** da una renderizzazione all'altra. Se la struttura è diversa, lo state viene distrutto perché React distrugge lo state quando rimuove un componente dall'albero.
-This is why you should not nest component function definitions.
+Ecco perché non dovresti annidare definizioni di funzioni componente.
-Here, the `MyTextField` component function is defined *inside* `MyComponent`:
+Qui, la funzione componente `MyTextField` è definita *dentro* `MyComponent`:
@@ -726,7 +733,7 @@ export default function MyComponent() {
+ }}>Cliccato {counter} volte
>
);
}
@@ -735,13 +742,13 @@ export default function MyComponent() {
-Every time you click the button, the input state disappears! This is because a *different* `MyTextField` function is created for every render of `MyComponent`. You're rendering a *different* component in the same position, so React resets all state below. This leads to bugs and performance problems. To avoid this problem, **always declare component functions at the top level, and don't nest their definitions.**
+Ogni volta che clicchi il pulsante, lo state dell'input scompare! Questo perché una funzione `MyTextField` *diversa* viene creata a ogni renderizzazione di `MyComponent`. Stai renderizzando un componente *diverso* nella stessa posizione, quindi React reimposta tutto lo state sotto. Questo porta a bug e problemi di performance. Per evitare questo problema, **dichiara sempre le funzioni componente al top level e non annidare le loro definizioni.**
-## Resetting state at the same position {/*resetting-state-at-the-same-position*/}
+## Reimpostare lo state nella stessa posizione {/*resetting-state-at-the-same-position*/}
-By default, React preserves state of a component while it stays at the same position. Usually, this is exactly what you want, so it makes sense as the default behavior. But sometimes, you may want to reset a component's state. Consider this app that lets two players keep track of their scores during each turn:
+Per impostazione predefinita, React preserva lo state di un componente finché resta nella stessa posizione. Di solito, è esattamente ciò che vuoi, quindi ha senso come comportamento predefinito. Ma a volte, potresti voler reimpostare lo state di un componente. Considera questa app che permette a due giocatori di tenere traccia dei propri punteggi durante ogni turno:
@@ -760,7 +767,7 @@ export default function Scoreboard() {
);
@@ -781,9 +788,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
Punteggio di {person}: {score}
);
@@ -811,19 +818,19 @@ h1 {
-Currently, when you change the player, the score is preserved. The two `Counter`s appear in the same position, so React sees them as *the same* `Counter` whose `person` prop has changed.
+Attualmente, quando cambi giocatore, il punteggio viene preservato. I due `Counter` appaiono nella stessa posizione, quindi React li vede come *lo stesso* `Counter` la cui prop `person` è cambiata.
-But conceptually, in this app they should be two separate counters. They might appear in the same place in the UI, but one is a counter for Taylor, and another is a counter for Sarah.
+Ma concettualmente, in questa app dovrebbero essere due contatori separati. Potrebbero apparire nello stesso posto nell'UI, ma uno è un contatore per Taylor e l'altro è un contatore per Sarah.
-There are two ways to reset state when switching between them:
+Ci sono due modi per reimpostare lo state quando passi da uno all'altro:
-1. Render components in different positions
-2. Give each component an explicit identity with `key`
+1. Renderizzare i componenti in posizioni diverse
+2. Dare a ciascun componente un'identità esplicita con `key`
-### Option 1: Rendering a component in different positions {/*option-1-rendering-a-component-in-different-positions*/}
+### Opzione 1: Renderizzare un componente in posizioni diverse {/*option-1-rendering-a-component-in-different-positions*/}
-If you want these two `Counter`s to be independent, you can render them in two different positions:
+Se vuoi che questi due `Counter` siano indipendenti, puoi renderizzarli in due posizioni diverse:
@@ -843,7 +850,7 @@ export default function Scoreboard() {
);
@@ -864,9 +871,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
Punteggio di {person}: {score}
);
@@ -894,42 +901,42 @@ h1 {
-* Initially, `isPlayerA` is `true`. So the first position contains `Counter` state, and the second one is empty.
-* When you click the "Next player" button the first position clears but the second one now contains a `Counter`.
+* Inizialmente, `isPlayerA` è `true`. Quindi la prima posizione contiene lo state di `Counter`, e la seconda è vuota.
+* Quando clicchi il pulsante "Giocatore successivo", la prima posizione si svuota ma la seconda ora contiene un `Counter`.
-
+
-Initial state
+State iniziale
-
+
-Clicking "next"
+Clic su "successivo"
-
+
-Clicking "next" again
+Clic su "successivo" di nuovo
-Each `Counter`'s state gets destroyed each time it's removed from the DOM. This is why they reset every time you click the button.
+Lo state di ciascun `Counter` viene distrutto ogni volta che viene rimosso dal DOM. Ecco perché si reimpostano ogni volta che clicchi il pulsante.
-This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX.
+Questa soluzione è comoda quando hai solo pochi componenti indipendenti renderizzati nello stesso posto. In questo esempio, ne hai solo due, quindi non è un problema renderizzarli separatamente nel JSX.
-### Option 2: Resetting state with a key {/*option-2-resetting-state-with-a-key*/}
+### Opzione 2: Reimpostare lo state con una key {/*option-2-resetting-state-with-a-key*/}
-There is also another, more generic, way to reset a component's state.
+C'è anche un altro modo, più generico, per reimpostare lo state di un componente.
-You might have seen `key`s when [rendering lists.](/learn/rendering-lists#keeping-list-items-in-order-with-key) Keys aren't just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent ("first counter", "second counter") to discern between components. But keys let you tell React that this is not just a *first* counter, or a *second* counter, but a specific counter--for example, *Taylor's* counter. This way, React will know *Taylor's* counter wherever it appears in the tree!
+Potresti aver visto le `key` quando [renderizzi liste.](/learn/rendering-lists#keeping-list-items-in-order-with-key) Le key non servono solo per le liste! Puoi usare le key per far distinguere a React qualsiasi componente. Per impostazione predefinita, React usa l'ordine all'interno del genitore ("primo contatore", "secondo contatore") per distinguere i componenti. Ma le key ti permettono di dire a React che questo non è solo un *primo* contatore, o un *secondo* contatore, ma un contatore specifico — ad esempio, il contatore di *Taylor*. In questo modo, React conoscerà il contatore di *Taylor* ovunque appaia nell'albero!
-In this example, the two ``s don't share state even though they appear in the same place in JSX:
+In questo esempio, i due `` non condividono lo state anche se appaiono nello stesso posto nel JSX:
@@ -948,7 +955,7 @@ export default function Scoreboard() {
);
@@ -969,9 +976,9 @@ function Counter({ person }) {
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
-
{person}'s score: {score}
+
Punteggio di {person}: {score}
);
@@ -999,7 +1006,7 @@ h1 {
-Switching between Taylor and Sarah does not preserve the state. This is because **you gave them different `key`s:**
+Passare tra Taylor e Sarah non preserva lo state. Questo perché **hai dato loro `key` diverse:**
```js
{isPlayerA ? (
@@ -1009,19 +1016,19 @@ Switching between Taylor and Sarah does not preserve the state. This is because
)}
```
-Specifying a `key` tells React to use the `key` itself as part of the position, instead of their order within the parent. This is why, even though you render them in the same place in JSX, React sees them as two different counters, and so they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed. Toggling between them resets their state over and over.
+Specificare una `key` dice a React di usare la `key` stessa come parte della posizione, invece del loro ordine all'interno del genitore. Ecco perché, anche se li renderizzi nello stesso posto nel JSX, React li vede come due contatori diversi, e quindi non condivideranno mai lo state. Ogni volta che un contatore appare sullo schermo, il suo state viene creato. Ogni volta che viene rimosso, il suo state viene distrutto. Alternare tra loro reimposta il loro state ogni volta.
-Remember that keys are not globally unique. They only specify the position *within the parent*.
+Ricorda che le key non sono univoche a livello globale. Specificano solo la posizione *all'interno del genitore*.
-### Resetting a form with a key {/*resetting-a-form-with-a-key*/}
+### Reimpostare un form con una key {/*resetting-a-form-with-a-key*/}
-Resetting state with a key is particularly useful when dealing with forms.
+Reimpostare lo state con una key è particolarmente utile quando si tratta di form.
-In this chat app, the `` component contains the text input state:
+In questa app di chat, il componente `` contiene lo state dell'input di testo:
@@ -1084,11 +1091,11 @@ export default function Chat({ contact }) {
);
}
@@ -1116,17 +1123,17 @@ textarea {
-Try entering something into the input, and then press "Alice" or "Bob" to choose a different recipient. You will notice that the input state is preserved because the `` is rendered at the same position in the tree.
+Prova a inserire qualcosa nell'input, e poi premi "Alice" o "Bob" per scegliere un destinatario diverso. Noterai che lo state dell'input viene preservato perché `` è renderizzato nella stessa posizione nell'albero.
-**In many apps, this may be the desired behavior, but not in a chat app!** You don't want to let the user send a message they already typed to a wrong person due to an accidental click. To fix it, add a `key`:
+**In molte app, questo potrebbe essere il comportamento desiderato, ma non in un'app di chat!** Non vuoi permettere all'utente di inviare a una persona sbagliata un messaggio che ha già digitato a causa di un clic accidentale. Per risolverlo, aggiungi una `key`:
```js
```
-This ensures that when you select a different recipient, the `Chat` component will be recreated from scratch, including any state in the tree below it. React will also re-create the DOM elements instead of reusing them.
+Questo garantisce che quando selezioni un destinatario diverso, il componente `Chat` verrà ricreato da zero, incluso qualsiasi state nell'albero sotto di esso. React ricreerà anche gli elementi DOM invece di riutilizzarli.
-Now switching the recipient always clears the text field:
+Ora cambiare destinatario svuota sempre il campo di testo:
@@ -1189,11 +1196,11 @@ export default function Chat({ contact }) {
);
}
@@ -1223,24 +1230,24 @@ textarea {
-#### Preserving state for removed components {/*preserving-state-for-removed-components*/}
+#### Preservare lo state per componenti rimossi {/*preserving-state-for-removed-components*/}
-In a real chat app, you'd probably want to recover the input state when the user selects the previous recipient again. There are a few ways to keep the state "alive" for a component that's no longer visible:
+In una vera app di chat, probabilmente vorresti recuperare lo state dell'input quando l'utente seleziona di nuovo il destinatario precedente. Ci sono alcuni modi per mantenere lo state "vivo" per un componente che non è più visibile:
-- You could render _all_ chats instead of just the current one, but hide all the others with CSS. The chats would not get removed from the tree, so their local state would be preserved. This solution works great for simple UIs. But it can get very slow if the hidden trees are large and contain a lot of DOM nodes.
-- You could [lift the state up](/learn/sharing-state-between-components) and hold the pending message for each recipient in the parent component. This way, when the child components get removed, it doesn't matter, because it's the parent that keeps the important information. This is the most common solution.
-- You might also use a different source in addition to React state. For example, you probably want a message draft to persist even if the user accidentally closes the page. To implement this, you could have the `Chat` component initialize its state by reading from the [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), and save the drafts there too.
+- Potresti renderizzare _tutte_ le chat invece di solo quella corrente, ma nascondere tutte le altre con CSS. Le chat non verrebbero rimosse dall'albero, quindi il loro state locale verrebbe preservato. Questa soluzione funziona benissimo per UI semplici. Ma può diventare molto lenta se gli alberi nascosti sono grandi e contengono molti nodi DOM.
+- Potresti [alzare lo state](/learn/sharing-state-between-components) e conservare il messaggio in sospeso per ciascun destinatario nel componente genitore. In questo modo, quando i componenti figli vengono rimossi, non importa, perché è il genitore che conserva le informazioni importanti. Questa è la soluzione più comune.
+- Potresti anche usare una fonte diversa oltre allo state di React. Ad esempio, probabilmente vuoi che una bozza di messaggio persista anche se l'utente chiude accidentalmente la pagina. Per implementarlo, potresti far inizializzare al componente `Chat` il suo state leggendo da [`localStorage`](https://developer.mozilla.org/it/docs/Web/API/Window/localStorage), e salvare le bozze lì.
-No matter which strategy you pick, a chat _with Alice_ is conceptually distinct from a chat _with Bob_, so it makes sense to give a `key` to the `` tree based on the current recipient.
+Indipendentemente dalla strategia che scegli, una chat _con Alice_ è concettualmente distinta da una chat _con Bob_, quindi ha senso dare una `key` all'albero `` in base al destinatario corrente.
-- React keeps state for as long as the same component is rendered at the same position.
-- State is not kept in JSX tags. It's associated with the tree position in which you put that JSX.
-- You can force a subtree to reset its state by giving it a different key.
-- Don't nest component definitions, or you'll reset state by accident.
+- React mantiene lo state finché lo stesso componente è renderizzato nella stessa posizione.
+- Lo state non è conservato nei tag JSX. È associato alla posizione nell'albero in cui metti quel JSX.
+- Puoi forzare un sottoalbero a reimpostare il suo state dandogli una key diversa.
+- Non annidare definizioni di componenti, altrimenti reimposterai lo state per sbaglio.
@@ -1248,9 +1255,9 @@ No matter which strategy you pick, a chat _with Alice_ is conceptually distinct
-#### Fix disappearing input text {/*fix-disappearing-input-text*/}
+#### Correggere il testo dell'input che scompare {/*fix-disappearing-input-text*/}
-This example shows a message when you press the button. However, pressing the button also accidentally resets the input. Why does this happen? Fix it so that pressing the button does not reset the input text.
+Questo esempio mostra un messaggio quando premi il pulsante. Tuttavia, premere il pulsante reimposta anche accidentalmente l'input. Perché succede? Correggilo in modo che premere il pulsante non reimposti il testo dell'input.
@@ -1262,11 +1269,11 @@ export default function App() {
if (showHint) {
return (
-
Hint: Your favorite city?
+
Suggerimento: La tua città preferita?
+ }}>Nascondi suggerimento
);
}
@@ -1275,7 +1282,7 @@ export default function App() {
+ }}>Mostra suggerimento
);
}
@@ -1299,9 +1306,9 @@ textarea { display: block; margin: 10px 0; }
-The problem is that `Form` is rendered in different positions. In the `if` branch, it is the second child of the `
`, but in the `else` branch, it is the first child. Therefore, the component type in each position changes. The first position changes between holding a `p` and a `Form`, while the second position changes between holding a `Form` and a `button`. React resets the state every time the component type changes.
+Il problema è che `Form` è renderizzato in posizioni diverse. Nel ramo `if`, è il secondo figlio del `
`, ma nel ramo `else`, è il primo figlio. Quindi, il tipo di componente in ciascuna posizione cambia. La prima posizione alterna tra contenere un `p` e un `Form`, mentre la seconda posizione alterna tra contenere un `Form` e un `button`. React reimposta lo state ogni volta che il tipo di componente cambia.
-The easiest solution is to unify the branches so that `Form` always renders in the same position:
+La soluzione più semplice è unificare i rami in modo che `Form` venga sempre renderizzato nella stessa posizione:
@@ -1313,17 +1320,17 @@ export default function App() {
return (
);
@@ -1347,7 +1354,7 @@ textarea { display: block; margin: 10px 0; }
-Technically, you could also add `null` before `` in the `else` branch to match the `if` branch structure:
+Tecnicamente, potresti anche aggiungere `null` prima di `` nel ramo `else` per corrispondere alla struttura del ramo `if`:
@@ -1359,11 +1366,11 @@ export default function App() {
if (showHint) {
return (
);
}
@@ -1395,19 +1402,19 @@ textarea { display: block; margin: 10px 0; }
-This way, `Form` is always the second child, so it stays in the same position and keeps its state. But this approach is much less obvious and introduces a risk that someone else will remove that `null`.
+In questo modo, `Form` è sempre il secondo figlio, quindi resta nella stessa posizione e mantiene il suo state. Ma questo approccio è molto meno ovvio e introduce il rischio che qualcun altro rimuova quel `null`.
-#### Swap two form fields {/*swap-two-form-fields*/}
+#### Scambiare due campi del form {/*swap-two-form-fields*/}
-This form lets you enter first and last name. It also has a checkbox controlling which field goes first. When you tick the checkbox, the "Last name" field will appear before the "First name" field.
+Questo form ti permette di inserire nome e cognome. Ha anche una checkbox che controlla quale campo va per primo. Quando selezioni la checkbox, il campo "Cognome" apparirà prima del campo "Nome".
-It almost works, but there is a bug. If you fill in the "First name" input and tick the checkbox, the text will stay in the first input (which is now "Last name"). Fix it so that the input text *also* moves when you reverse the order.
+Funziona quasi, ma c'è un bug. Se compili l'input "Nome" e selezioni la checkbox, il testo resterà nel primo input (che ora è "Cognome"). Correggilo in modo che il testo dell'input *si sposti* anche quando inverti l'ordine.
-It seems like for these fields, their position within the parent is not enough. Is there some way to tell React how to match up the state between re-renders?
+Sembra che per questi campi, la loro posizione all'interno del genitore non basti. C'è un modo per dire a React come abbinare lo state tra le ri-renderizzazioni?
@@ -1425,22 +1432,22 @@ export default function App() {
checked={reverse}
onChange={e => setReverse(e.target.checked)}
/>
- Reverse order
+ Ordine inverso
);
if (reverse) {
return (
<>
-
-
+
+
{checkbox}
>
);
} else {
return (
<>
-
-
+
+
{checkbox}
>
);
@@ -1471,7 +1478,7 @@ label { display: block; margin: 10px 0; }
-Give a `key` to both `` components in both `if` and `else` branches. This tells React how to "match up" the correct state for either `` even if their order within the parent changes:
+Dai una `key` a entrambi i componenti `` in entrambi i rami `if` e `else`. Questo dice a React come "abbinare" lo state corretto per ciascun `` anche se il loro ordine all'interno del genitore cambia:
@@ -1487,22 +1494,22 @@ export default function App() {
checked={reverse}
onChange={e => setReverse(e.target.checked)}
/>
- Reverse order
+ Ordine inverso
);
if (reverse) {
return (
<>
-
-
+
+
{checkbox}
>
);
} else {
return (
<>
-
-
+
+
{checkbox}
>
);
@@ -1533,11 +1540,11 @@ label { display: block; margin: 10px 0; }
-#### Reset a detail form {/*reset-a-detail-form*/}
+#### Reimpostare un form di dettaglio {/*reset-a-detail-form*/}
-This is an editable contact list. You can edit the selected contact's details and then either press "Save" to update it, or "Reset" to undo your changes.
+Questa è una lista di contatti modificabile. Puoi modificare i dettagli del contatto selezionato e poi premere "Salva" per aggiornarlo, o "Reimposta" per annullare le modifiche.
-When you select a different contact (for example, Alice), the state updates but the form keeps showing the previous contact's details. Fix it so that the form gets reset when the selected contact changes.
+Quando selezioni un contatto diverso (ad esempio, Alice), lo state viene aggiornato ma il form continua a mostrare i dettagli del contatto precedente. Correggilo in modo che il form venga reimpostato quando cambia il contatto selezionato.
@@ -1629,7 +1636,7 @@ export default function EditContact({ initialData, onSave }) {
return (
);
@@ -1689,7 +1696,7 @@ button {
-Give `key={selectedId}` to the `EditContact` component. This way, switching between different contacts will reset the form:
+Dai `key={selectedId}` al componente `EditContact`. In questo modo, passare tra contatti diversi reimposterà il form:
@@ -1782,7 +1789,7 @@ export default function EditContact({ initialData, onSave }) {
return (
);
@@ -1842,13 +1849,13 @@ button {
-#### Clear an image while it's loading {/*clear-an-image-while-its-loading*/}
+#### Svuotare un'immagine mentre si carica {/*clear-an-image-while-its-loading*/}
-When you press "Next", the browser starts loading the next image. However, because it's displayed in the same `` tag, by default you would still see the previous image until the next one loads. This may be undesirable if it's important for the text to always match the image. Change it so that the moment you press "Next", the previous image immediately clears.
+Quando premi "Successivo", il browser inizia a caricare l'immagine successiva. Tuttavia, poiché viene visualizzata nello stesso tag ``, per impostazione predefinita vedresti ancora l'immagine precedente finché la successiva non si carica. Questo può essere indesiderabile se è importante che il testo corrisponda sempre all'immagine. Modificalo in modo che nel momento in cui premi "Successivo", l'immagine precedente si svuoti immediatamente.
-Is there a way to tell React to re-create the DOM instead of reusing it?
+C'è un modo per dire a React di ricreare il DOM invece di riutilizzarlo?
@@ -1873,10 +1880,10 @@ export default function Gallery() {
return (
<>
- Image {index + 1} of {images.length}
+ Immagine {index + 1} di {images.length}
@@ -1918,7 +1925,7 @@ img { width: 150px; height: 150px; }
-You can provide a `key` to the `` tag. When that `key` changes, React will re-create the `` DOM node from scratch. This causes a brief flash when each image loads, so it's not something you'd want to do for every image in your app. But it makes sense if you want to ensure the image always matches the text.
+Puoi fornire una `key` al tag ``. Quando quella `key` cambia, React ricreerà il nodo DOM `` da zero. Questo causa un breve flash quando ogni immagine si carica, quindi non è qualcosa che vorresti fare per ogni immagine nella tua app. Ma ha senso se vuoi assicurarti che l'immagine corrisponda sempre al testo.
@@ -1941,10 +1948,10 @@ export default function Gallery() {
return (
<>
- Image {index + 1} of {images.length}
+ Immagine {index + 1} di {images.length}
-#### Fix misplaced state in the list {/*fix-misplaced-state-in-the-list*/}
+#### Correggere lo state fuori posto nella lista {/*fix-misplaced-state-in-the-list*/}
-In this list, each `Contact` has state that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's _Taylor's_ email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed.
+In questa lista, ogni `Contact` ha uno state che determina se "Mostra email" è stato premuto per esso. Premi "Mostra email" per Alice, e poi seleziona la checkbox "Mostra in ordine inverso". Noterai che è l'email di _Taylor_ ad essere espansa ora, ma quella di Alice — che si è spostata in fondo — appare collassata.
-Fix it so that the expanded state is associated with each contact, regardless of the chosen ordering.
+Correggilo in modo che lo state espanso sia associato a ciascun contatto, indipendentemente dall'ordinamento scelto.
@@ -2016,7 +2023,7 @@ export default function ContactList() {
setReverse(e.target.checked)
}}
/>{' '}
- Show in reverse order
+ Mostra in ordine inverso
{displayedContacts.map((contact, i) =>
@@ -2050,7 +2057,7 @@ export default function Contact({ contact }) {
>
);
@@ -2080,16 +2087,16 @@ button {
-The problem is that this example was using index as a `key`:
+Il problema è che questo esempio usava l'indice come `key`:
```js
{displayedContacts.map((contact, i) =>
```
-However, you want the state to be associated with _each particular contact_.
+Tuttavia, vuoi che lo state sia associato a _ciascun contatto specifico_.
-Using the contact ID as a `key` instead fixes the issue:
+Usare l'ID del contatto come `key` risolve il problema:
@@ -2115,7 +2122,7 @@ export default function ContactList() {
setReverse(e.target.checked)
}}
/>{' '}
- Show in reverse order
+ Mostra in ordine inverso
-State is associated with the tree position. A `key` lets you specify a named position instead of relying on order.
+Lo state è associato alla posizione nell'albero. Una `key` ti permette di specificare una posizione nominata invece di basarti sull'ordine.
diff --git a/src/sidebarLearn.json b/src/sidebarLearn.json
index 44c3228e1..e0c0635a9 100644
--- a/src/sidebarLearn.json
+++ b/src/sidebarLearn.json
@@ -181,7 +181,7 @@
"path": "/learn/sharing-state-between-components"
},
{
- "title": "Preserving and Resetting State",
+ "title": "Preservare e Reimpostare lo State",
"path": "/learn/preserving-and-resetting-state"
},
{