Skip to content

Commit 97c6823

Browse files
committed
translate(learn-react): You Might Not Need An Effect
Second batch of translations
1 parent 6aa4cb9 commit 97c6823

File tree

1 file changed

+30
-30
lines changed

1 file changed

+30
-30
lines changed

src/content/learn/you-might-not-need-an-effect.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -302,19 +302,19 @@ Questo rimuove l'Effetto inutile e contemporaneamente risolve il bug.
302302
303303
### Inviare una richiesta POST {/*sending-a-post-request*/}
304304
305-
Questo componente `Form` invia due tipi di richieste POST. It sends an analytics event when it mounts. When you fill in the form and click the Submit button, it will send a POST request to the `/api/register` endpoint:
305+
Questo componente `Form` invia due tipi di richieste POST. Invia un evento di analytics dopo il mounting. Quando riempi il form e clicchi sul pulsante di Submit, invia una richiesta POST sull'endpoint `/api/register`:
306306
307307
```js {5-8,10-16}
308308
function Form() {
309309
const [firstName, setFirstName] = useState('');
310310
const [lastName, setLastName] = useState('');
311311

312-
//Good: This logic should run because the component was displayed
312+
//Buono: Questa logica funzionerà perché il componente è stato già mostrato
313313
useEffect(() => {
314314
post('/analytics/event', { eventName: 'visit_form' });
315315
}, []);
316316

317-
// 🔴 Avoid: Event-specific logic inside an Effect
317+
// 🔴 Evita: logica specifica di un evento in un Effetto.
318318
const [jsonToSubmit, setJsonToSubmit] = useState(null);
319319
useEffect(() => {
320320
if (jsonToSubmit !== null) {
@@ -330,36 +330,36 @@ function Form() {
330330
}
331331
```
332332
333-
Let's apply the same criteria as in the example before.
333+
Applichiamo lo stesso criterio dell'esempio precedente.
334334
335-
The analytics POST request should remain in an Effect. This is because the _reason_ to send the analytics event is that the form was displayed. (It would fire twice in development, but [see here](/learn/synchronizing-with-effects#sending-analytics) for how to deal with that.)
335+
la richiesta POST di analytics dovrebbe rimanere in un Effetto. Questo perché il _motivo_ per inviare un evento di analytics è che il form viene mostrato. (Dovrebbe eseguire due volte in modalità di sviluppo, [leggi qui](/learn/synchronizing-with-effects#sending-analytics) per capire come gestirlo.)
336336
337-
However, the `/api/register` POST request is not caused by the form being _displayed_. You only want to send the request at one specific moment in time: when the user presses the button. It should only ever happen _on that particular interaction_. Delete the second Effect and move that POST request into the event handler:
337+
Comunque, la richiesta POST `/api/register` non è causata dal fatto che il Form viene _mostrato_. Vuoi soltanto inviare la richiesta in un momento specifico nel tempo: quando l'utente preme il pulsante. Dovrebbe succedere _solo in quella interazione specifica_. Elimina il secondo Effetto e sposta la richiesta POST nell'event handler:
338338
339339
```js {12-13}
340340
function Form() {
341341
const [firstName, setFirstName] = useState('');
342342
const [lastName, setLastName] = useState('');
343343

344-
//Good: This logic runs because the component was displayed
344+
//Buono: Questa logica funziona perché l'evento è stato mostrato
345345
useEffect(() => {
346346
post('/analytics/event', { eventName: 'visit_form' });
347347
}, []);
348348

349349
function handleSubmit(e) {
350350
e.preventDefault();
351-
//Good: Event-specific logic is in the event handler
351+
//Buona: La logica specifica dell'evento è nel suo event handler
352352
post('/api/register', { firstName, lastName });
353353
}
354354
// ...
355355
}
356356
```
357357
358-
When you choose whether to put some logic into an event handler or an Effect, the main question you need to answer is _what kind of logic_ it is from the user's perspective. If this logic is caused by a particular interaction, keep it in the event handler. If it's caused by the user _seeing_ the component on the screen, keep it in the Effect.
358+
Quando devi scegliere se inserire della logica in un event handler o in un Effetto, la domanda principale a cui devi rispondere è _che tipo di logica_ è dal punto di vista dell'utente. Se è logica causata da una interazione particolare, mantienila nel suo event handler. Se è causata dal fatto che l'utente sta _vedendo_ il componente sullo schermo, mantienila nell'Effetto.
359359
360-
### Chains of computations {/*chains-of-computations*/}
360+
### Catena di computazione {/*chains-of-computations*/}
361361
362-
Sometimes you might feel tempted to chain Effects that each adjust a piece of state based on other state:
362+
A volte puoi essere tentato di concatenare Effetti che modificano un pezzo di state basandosi su altro state:
363363
364364
```js {7-29}
365365
function Game() {
@@ -368,7 +368,7 @@ function Game() {
368368
const [round, setRound] = useState(1);
369369
const [isGameOver, setIsGameOver] = useState(false);
370370

371-
// 🔴 Avoid: Chains of Effects that adjust the state solely to trigger each other
371+
// 🔴 Evita: Catene di Effetti che modificano lo stato soltanto per scatenare altri Effetti
372372
useEffect(() => {
373373
if (card !== null && card.gold) {
374374
setGoldCardCount(c => c + 1);
@@ -403,29 +403,29 @@ function Game() {
403403
// ...
404404
```
405405
406-
There are two problems with this code.
406+
Ci sono due problemi con questo codice:
407407
408-
One problem is that it is very inefficient: the component (and its children) have to re-render between each `set` call in the chain. In the example above, in the worst case (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) there are three unnecessary re-renders of the tree below.
408+
Un problema è che è molto inefficiente: il componente (e i suoi figli) devono re-renderizzare tra ogni chiamata `set` nella catena. Nell'esempio su, nel caso peggiore (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) ci sono tre re-renders non necessari dell'albero sottostante.
409409
410-
Even if it weren't slow, as your code evolves, you will run into cases where the "chain" you wrote doesn't fit the new requirements. Imagine you are adding a way to step through the history of the game moves. You'd do it by updating each state variable to a value from the past. However, setting the `card` state to a value from the past would trigger the Effect chain again and change the data you're showing. Such code is often rigid and fragile.
410+
Anche se non è lento, con l'evolversi del codice, andrai incontro a casi in cui la "catena" che hai scritto non soddisfa i requisiti. Immagina che stai aggiungendo un modo per muoverti attraverso lo storico dei movimenti di un gioco. Lo faresti aggiornando ogni variabile di state dal passato. Tuttavia, impostare lo state `card` da un valore passato azionerebbe la catena dell'Effetto nuovamente e cambierebbe i dati che stai mostrando. Il codice così è rigido e fragile.
411411
412-
In this case, it's better to calculate what you can during rendering, and adjust the state in the event handler:
412+
In questo caso, è meglio calcolare ciò che puoi durante il rendering, e regolare lo state nell'event handler:
413413
414414
```js {6-7,14-26}
415415
function Game() {
416416
const [card, setCard] = useState(null);
417417
const [goldCardCount, setGoldCardCount] = useState(0);
418418
const [round, setRound] = useState(1);
419419

420-
//Calculate what you can during rendering
420+
//Calcola ciò che puoi durante il rendering
421421
const isGameOver = round > 5;
422422

423423
function handlePlaceCard(nextCard) {
424424
if (isGameOver) {
425425
throw Error('Game already ended.');
426426
}
427427

428-
//Calculate all the next state in the event handler
428+
//Calcola il prossimo state nell'event handler
429429
setCard(nextCard);
430430
if (nextCard.gold) {
431431
if (goldCardCount <= 3) {
@@ -443,21 +443,21 @@ function Game() {
443443
// ...
444444
```
445445
446-
This is a lot more efficient. Also, if you implement a way to view game history, now you will be able to set each state variable to a move from the past without triggering the Effect chain that adjusts every other value. If you need to reuse logic between several event handlers, you can [extract a function](#sharing-logic-between-event-handlers) and call it from those handlers.
446+
Questo è molto più efficiente. Inoltre, se implementi un modo per vedere lo storico della partita, ora sei capace di muovere ogni variabile di state nel passato senza azionare la catena dovuta all'Effetto che regola ogni altro valore. Se necessiti di riutilizzare logica tra diversi event handlers, puoi [estrarre una funzione](#sharing-logic-between-event-handlers) e chiamarla al loro interno.
447447
448-
Remember that inside event handlers, [state behaves like a snapshot.](/learn/state-as-a-snapshot) For example, even after you call `setRound(round + 1)`, the `round` variable will reflect the value at the time the user clicked the button. If you need to use the next value for calculations, define it manually like `const nextRound = round + 1`.
448+
Ricorda che negli event handlers, [lo state si comporta come un'istantanea.](/learn/state-as-a-snapshot) Per esempio, anche dopo aver chiamato `setRound(round + 1)`, la variabile di state `round` corrisponderà al valore che aveva quando l' utente ha cliccato sul pulsante. Se hai bisogno del prossimo valore per effettuare calcoli, definiscilo manualmente in modo simile a questo: `const nextRound = round + 1`.
449449
450-
In some cases, you *can't* calculate the next state directly in the event handler. For example, imagine a form with multiple dropdowns where the options of the next dropdown depend on the selected value of the previous dropdown. Then, a chain of Effects is appropriate because you are synchronizing with network.
450+
In alcuni casi, *non puoi* calcolare il prossimo stato direttamente nell'event handler. Per esempio, immagina un form con dropdowns multiple in cui la option della prossima dropdown dipende dal valore selezionato in quella precedente. In questo caso, una catena di Effetti è appropriata perché stai sincronizzando lo state con la rete.
451451
452-
### Initializing the application {/*initializing-the-application*/}
452+
### Inizializzando l'applicazione {/*initializing-the-application*/}
453453
454-
Some logic should only run once when the app loads.
454+
Alcune logiche dovrebbero partire solo una volta dopo che l'app viene caricata.
455455
456-
You might be tempted to place it in an Effect in the top-level component:
456+
Potresti essere tentato di inserirla in un Effetto al componente di primo livello:
457457
458458
```js {2-6}
459459
function App() {
460-
// 🔴 Avoid: Effects with logic that should only ever run once
460+
// 🔴 Evita: Effetti con logica che dovrebbe eseguire una volta sola
461461
useEffect(() => {
462462
loadDataFromLocalStorage();
463463
checkAuthToken();
@@ -466,9 +466,9 @@ function App() {
466466
}
467467
```
468468
469-
However, you'll quickly discover that it [runs twice in development.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) This can cause issues--for example, maybe it invalidates the authentication token because the function wasn't designed to be called twice. In general, your components should be resilient to being remounted. This includes your top-level `App` component.
469+
Tuttavia, scoprirai presto che [gira due volte in modalità di sviluppo.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) Questo può causare problemi--per esempio, potrebbe invalidare il token di autenticazione perché la funzione non era stata progettata per essere chiamata due volte. In generale, i tuoi componenti dovrebbero essere resilienti quando vengono rimontati. Includendo il componente di primo livello `App`.
470470
471-
Although it may not ever get remounted in practice in production, following the same constraints in all components makes it easier to move and reuse code. If some logic must run *once per app load* rather than *once per component mount*, add a top-level variable to track whether it has already executed:
471+
Anche se in produzione potrebbe non essere smontato mai, seguire gli stessi vincoli in tutti i componenti rende più facile muovere e riutilizzare codice. Se della logica deve eseguire *una volta per caricamento dell'app* invece che *una volta ogni volta che il componente viene montato*, aggiungi una variabile al primo livello per tracciarne l'esecuzione:
472472
473473
```js {1,5-6,10}
474474
let didInit = false;
@@ -477,7 +477,7 @@ function App() {
477477
useEffect(() => {
478478
if (!didInit) {
479479
didInit = true;
480-
//Only runs once per app load
480+
//Esegue una volta quando l'app carica
481481
loadDataFromLocalStorage();
482482
checkAuthToken();
483483
}
@@ -486,11 +486,11 @@ function App() {
486486
}
487487
```
488488
489-
You can also run it during module initialization and before the app renders:
489+
Puoi anche eseguirlo durante l'inizializzazione del modulo e prima della renderizzazione dell'app:
490490
491491
```js {1,5}
492492
if (typeof window !== 'undefined') { // Check if we're running in the browser.
493-
//Only runs once per app load
493+
//Esegue una volta quando l'app carica
494494
checkAuthToken();
495495
loadDataFromLocalStorage();
496496
}

0 commit comments

Comments
 (0)