From 19f214879929d6096cd56bedea543733519fe048 Mon Sep 17 00:00:00 2001 From: "Dennis A. Boanini" Date: Sat, 24 Apr 2021 00:15:49 +0200 Subject: [PATCH 01/15] Error boundaries translation --- content/docs/error-boundaries.md | 83 ++++++++++++++++---------------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/content/docs/error-boundaries.md b/content/docs/error-boundaries.md index 4c63959ca..04b35a118 100644 --- a/content/docs/error-boundaries.md +++ b/content/docs/error-boundaries.md @@ -4,25 +4,26 @@ title: Contenitori di Errori permalink: docs/error-boundaries.html --- -In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to [emit](https://github.com/facebook/react/issues/4026) [cryptic](https://github.com/facebook/react/issues/6895) [errors](https://github.com/facebook/react/issues/8579) on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them. +In passato gli errori JavaScript all'interno dei componenti erano usati per corrompere lo stato interno di React e causavano l'[emissione](https://github.com/facebook/react/issues/4026) di [errori](https://github.com/facebook/react/issues/8579) [criptici](https://github.com/facebook/react/issues/6895) nei rendering successivi. Questi errori erano sempre causati da un errore precedente nel codice dell'applicazione, ma React non forniva nessun modo per poterli gestire correttamente nei componenti e non poteva ripristinarli. -## Introducing Error Boundaries {#introducing-error-boundaries} +## Introduzione ai contenitori di errori {#introducing-error-boundaries} -A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”. +Un errore JavaScript in una qualche parte della UI non dovrebbe rompere l'intera applicazione. Per risolvere questo problema, a partire dalla versione 16 di React, viene introdotto il concetto di "contenitore di errori (error boundary)". -Error boundaries are React components that **catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI** instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. +I contenitori di errori sono componenti React che **catturano gli errori JavaScript in uno qualsiasi dei componenti figli nell'albero dei componenti, loggano gli errori e mostrano, all'utente, una UI di fallback** anziché mostrare il componente che ha causato l'errore. I contenitori di errore catturano gli errori durante il rendering, nei metodi del ciclo di vita di un componente e nei costruttori dell'intero albero di componenti sottostante. -> Note +> Nota > > Error boundaries do **not** catch errors for: +> I contenitori di errore non catturano gli errori di: > -> * Event handlers ([learn more](#how-about-event-handlers)) -> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks) -> * Server side rendering -> * Errors thrown in the error boundary itself (rather than its children) +> * Gestore di eventi ([approfondisci](#how-about-event-handlers)) +> * Codice asincrono (come ad esempio le callback `setTimeout` o `requestAnimationFrame`) +> * Rendering lato server +> * Errori sollevati all'interno del contenitore stesso (piuttosto che nei suoi figli) -A class component becomes an error boundary if it defines either (or both) of the lifecycle methods [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) or [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Use `static getDerivedStateFromError()` to render a fallback UI after an error has been thrown. Use `componentDidCatch()` to log error information. +Un componente basato su classe diventa un contenitore di errori se definisce uno, o entrambi, i metodi del ciclo di vita [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) e [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Utilizza `static getDerivedStateFromError()` per renderizzare una UI di fallback dopo che l'errore è stato sollevato. Utilizzate `componentDidCatch()` per loggare informazioni sull'errore. ```js{7-10,12-15,18-21} class ErrorBoundary extends React.Component { @@ -52,7 +53,7 @@ class ErrorBoundary extends React.Component { } ``` -Then you can use it as a regular component: +Dopodiché lo si può utilizzare come un normalissimo componente: ```js @@ -60,53 +61,53 @@ Then you can use it as a regular component: ``` -Error boundaries work like a JavaScript `catch {}` block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application. +I contenitori di errore lavorano all'incirca come il `catch {}` di JavaScript, ma sottoforma di componente. Solamente i componenti di tipo classe possono essere contenitori di errori. In pratica, nella maggioranza dei casi, si vuole scrivere un contenitore di errori una sola volta, per poi riutilizzarlo ovunque nell'applicazione. -Note that **error boundaries only catch errors in the components below them in the tree**. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how catch {} block works in JavaScript. +Da notare che **i contenitori di errori catturano gli errori solo nei componenti sottostanti nell'albero dei componenti** Un contenitore di errori non può catturare errori all'interno di se stesso. Se un contenitore di errore fallisce mentre prova a renderizzare il messaggio di errore, l'errore viene propagato sopra di lui al più vicino contenitore di errori sopra di lui. Anche questo aspetto è molto simile a come funzione il blocco `catch {}` di JavaScript. -## Live Demo {#live-demo} +## Demo {#live-demo} -Check out [this example of declaring and using an error boundary](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) with [React 16](/blog/2017/09/26/react-v16.0.html). +Guarda [questo esempio di dichiarazione e utilizzo di un contenitore di errori](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) fatto con [React 16](/blog/2017/09/26/react-v16.0.html). -## Where to Place Error Boundaries {#where-to-place-error-boundaries} +## Dove si dichiarano i contenitori di errori? {#where-to-place-error-boundaries} -The granularity of error boundaries is up to you. You may wrap top-level route components to display a “Something went wrong” message to the user, just like how server-side frameworks often handle crashes. You may also wrap individual widgets in an error boundary to protect them from crashing the rest of the application. +La granularità dei contenitori di errori dipende interamente da te sviluppatore. Potresti voler wrappare i componenti di rotte di primo livello facendo vedere un messaggio, all'utente, tipo "Qualcosa è andato storto" proprio come i framework lato server, spesso, gestiscono i crash. Potresti anche voler wrappare singoli widget all'interno di un contenitore di errori per proteggerli dai crash che possono succedere all'interno dell'applicazione. -## New Behavior for Uncaught Errors {#new-behavior-for-uncaught-errors} +## Nuovi comportamenti per errori non rilevati {#new-behavior-for-uncaught-errors} -This change has an important implication. **As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.** +Questi cambiamenti hanno un'importante implicazione. **A partire dalla versione 16 di React, gli errori che non vengono catturati da nessun contenitore di errori, porteranno allo smontaggio dell'intero albero dei componenti di React**. -We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing. +Abbiamo discusso molto prima di prendere questa decisione ma, secondo la nostra esperienza è peggio lasciare una UI rotta piuttosto che rimuoverla completamente. Ad esempio, in prodotti come Messenger, lasciare visibile una UI rotta può portare qualcuno a mandare un messaggio alla persona sbagliata. In modo simile, in un'applicazione di pagamenti è peggiore mostrare un importo sbagliato piuttosto che non far vedere nulla. -This change means that as you migrate to React 16, you will likely uncover existing crashes in your application that have been unnoticed before. Adding error boundaries lets you provide better user experience when something goes wrong. +Questi cambiamenti significano che se migrate verso React 16 probabilmente scoprirete, all'interno della vostra applicazione, dei crash che prima venivano ignorati. Aggiungere contenitori di errori vi aiuta a fornire una migliore user experience quando qualcosa va storto. -For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive. +Ad esempio Facebook Messenger wrappa il contenuto della barra laterale, del pannello informativo, delle conversazioni e dei messaggi di input in contenitori di errori separati. Se qualche componente in una delle precedenti aree si rompo, il resto dell'applicazione rimane comunque interattiva. -We also encourage you to use JS error reporting services (or build your own) so that you can learn about unhandled exceptions as they happen in production, and fix them. +Vi incoraggiamo inoltre ad utilizzare dei servizi JavaScript di reportistica (o costruitene una personalizzato) cosicché da capire che tipo di eccezioni vengono sollevate in produzione, e che non vengono catturate, e fixarle. -## Component Stack Traces {#component-stack-traces} +## Stack trace dei componenti {#component-stack-traces} -React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened: +La versione 16 di React stampa tutti gli errori, che vengono sollevati durante il rendering, nella console degli sviluppatori, anche se l'applicazione accidentamente li nasconde. Oltre al messaggio di errore, e allo stack JavaScript, React 16 fornisce anche lo stack trace dei componenti. Si può vedere esattamente dove, nell'albero dei componenti, sta l'errore: Error caught by Error Boundary component -You can also see the filenames and line numbers in the component stack trace. This works by default in [Create React App](https://github.com/facebookincubator/create-react-app) projects: +E' anche possibile vedere i nomi dei fili e i numeri di linea nello stack trace del componente. Questo è il comportamento di default nei progetti creati con [Create React App](https://github.com/facebookincubator/create-react-app): Error caught by Error Boundary component with line numbers -If you don’t use Create React App, you can add [this plugin](https://www.npmjs.com/package/@babel/plugin-transform-react-jsx-source) manually to your Babel configuration. Note that it’s intended only for development and **must be disabled in production**. +Se avete creato l'applicazione senza usare Create React App, potete usare [questo plugin] da aggiungere, manualmente, alla configurazione Babel. Tieni presente che tutto ciò vale solo per l'ambiente di sviluppo e **deve essere disabilitato in produzione**. -> Note +> Nota > -> Component names displayed in the stack traces depend on the [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property. If you support older browsers and devices which may not yet provide this natively (e.g. IE 11), consider including a `Function.name` polyfill in your bundled application, such as [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternatively, you may explicitly set the [`displayName`](/docs/react-component.html#displayname) property on all your components. +> I nomi dei componenti visualizzati nello stack trace dipendono dalla proprietà [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name). Se fornite supporto a browser vecchi che non forniscono questa cosa nativamente (come ad esempio IE 11), potete prendere in considerazione di includere il polyfill `Function.name` all'interno del bundle dell'applicazione, come ad esempio [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternativamente possiamo, esplicitamente, settare la proprietà [`displayName`](/docs/react-component.html#displayname) su tutti i componenti. -## How About try/catch? {#how-about-trycatch} +## Che dire di try/catch? {#how-about-trycatch} -`try` / `catch` is great but it only works for imperative code: +`try` / `catch` è ottimo ma funziona solo per codice imperativo: ```js try { @@ -116,21 +117,21 @@ try { } ``` -However, React components are declarative and specify *what* should be rendered: +Tuttavia i compoenti di React sono molto dichiarativi e specificano cosa deve essere renderizzato: ```js