diff --git a/src/content/learn/keeping-components-pure.md b/src/content/learn/keeping-components-pure.md
index 087f0e26e..d132633cc 100644
--- a/src/content/learn/keeping-components-pure.md
+++ b/src/content/learn/keeping-components-pure.md
@@ -1,41 +1,41 @@
---
-title: Keeping Components Pure
+title: Mantendo Componentes Puros
---
-Some JavaScript functions are *pure.* Pure functions only perform a calculation and nothing more. By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. To get these benefits, though, there are a few rules you must follow.
+Algumas funções JavaScript são *puras*. Funções puras apenas executam um cálculo e nada mais. Escrevendo seus componentes estritamente como funções puras, você pode evitar toda uma classe de erros desconcertantes e comportamento imprevisível à medida que seu código base cresce. No entanto, para obter esses benefícios, existem algumas regras que você deve seguir.
-* What purity is and how it helps you avoid bugs
-* How to keep components pure by keeping changes out of the render phase
-* How to use Strict Mode to find mistakes in your components
+* O que é pureza e como ela ajuda você a evitar erros
+* Como manter os componentes puros, mantendo as alterações fora da fase de renderização
+* Como usar o Modo Estrito para encontrar erros em seus componentes
-## Purity: Components as formulas {/*purity-components-as-formulas*/}
+## Pureza: Componentes como fórmulas {/*purity-components-as-formulas*/}
-In computer science (and especially the world of functional programming), [a pure function](https://wikipedia.org/wiki/Pure_function) is a function with the following characteristics:
+Em ciência da computação (e especialmente no mundo da programação funcional), [uma função pura](https://wikipedia.org/wiki/Pure_function) é uma função com as seguintes características:
-* **It minds its own business.** It does not change any objects or variables that existed before it was called.
-* **Same inputs, same output.** Given the same inputs, a pure function should always return the same result.
+* **Ela cuida de seus próprios negócios.** Ela não altera nenhum objeto ou variável que existia antes de ela ser chamada.
+* **Mesmas entradas, mesma saída.** Dadas as mesmas entradas, uma função pura deve sempre retornar o mesmo resultado.
-You might already be familiar with one example of pure functions: formulas in math.
+Você pode já estar familiarizado com um exemplo de funções puras: fórmulas em matemática.
-Consider this math formula: .
+Considere esta fórmula matemática: .
-If then . Always.
+Se então . Sempre.
-If then . Always.
+Se então . Sempre.
-If , y won't sometimes be or or depending on the time of day or the state of the stock market.
+Se , y às vezes não será ou ou dependendo da hora do dia ou do estado do mercado de ações.
-If and , y will _always_ be .
+Se e , y _sempre_ será .
-If we made this into a JavaScript function, it would look like this:
+Se fizéssemos isso em uma função JavaScript, ficaria assim:
```js
function double(number) {
@@ -43,9 +43,9 @@ function double(number) {
}
```
-In the above example, `double` is a **pure function.** If you pass it `3`, it will return `6`. Always.
+No exemplo acima, `double` é uma **função pura.** Se você passar `3`, ela retornará `6`. Sempre.
-React is designed around this concept. **React assumes that every component you write is a pure function.** This means that React components you write must always return the same JSX given the same inputs:
+React é projetado em torno desse conceito. **React assume que todo componente que você escreve é uma função pura.** Isso significa que os componentes React que você escreve devem sempre retornar o mesmo JSX dadas as mesmas entradas:
@@ -53,9 +53,9 @@ React is designed around this concept. **React assumes that every component you
function Recipe({ drinkers }) {
return (
- - Boil {drinkers} cups of water.
- - Add {drinkers} spoons of tea and {0.5 * drinkers} spoons of spice.
- - Add {0.5 * drinkers} cups of milk to boil and sugar to taste.
+ - Ferva {drinkers} xícaras de água.
+ - Adicione {drinkers} colheres de chá de chá e {0.5 * drinkers} colheres de chá de especiaria.
+ - Adicione {0.5 * drinkers} xícaras de leite para ferver e açúcar a gosto.
);
}
@@ -63,10 +63,10 @@ function Recipe({ drinkers }) {
export default function App() {
return (
- Spiced Chai Recipe
- For two
+ Receita de Chai com Especiarias
+ Para dois
- For a gathering
+ Para uma reunião
);
@@ -75,21 +75,21 @@ export default function App() {
-When you pass `drinkers={2}` to `Recipe`, it will return JSX containing `2 cups of water`. Always.
+Quando você passa `drinkers={2}` para `Recipe`, ele retornará JSX contendo `2 xícaras de água`. Sempre.
-If you pass `drinkers={4}`, it will return JSX containing `4 cups of water`. Always.
+Se você passar `drinkers={4}`, ele retornará JSX contendo `4 xícaras de água`. Sempre.
-Just like a math formula.
+Assim como uma fórmula matemática.
-You could think of your components as recipes: if you follow them and don't introduce new ingredients during the cooking process, you will get the same dish every time. That "dish" is the JSX that the component serves to React to [render.](/learn/render-and-commit)
+Você pode pensar em seus componentes como receitas: se você as seguir e não introduzir novos ingredientes durante o processo de cozimento, você obterá o mesmo prato toda vez. Esse "prato" é o JSX que o componente serve ao React para [renderizar.](/learn/render-and-commit)
-
+
-## Side Effects: (un)intended consequences {/*side-effects-unintended-consequences*/}
+## Efeitos colaterais: consequências (não)intencionais {/*side-effects-unintended-consequences*/}
-React's rendering process must always be pure. Components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure!
+O processo de renderização do React deve ser sempre puro. Os componentes devem apenas *retornar* seu JSX e não *alterar* nenhum objeto ou variável que existia antes da renderização — isso os tornaria impuros!
-Here is a component that breaks this rule:
+Aqui está um componente que quebra essa regra:
@@ -97,9 +97,9 @@ Here is a component that breaks this rule:
let guest = 0;
function Cup() {
- // Bad: changing a preexisting variable!
+ // Ruim: mudando uma variável pré-existente!
guest = guest + 1;
- return Tea cup for guest #{guest}
;
+ return Xícara de chá para o convidado #{guest}
;
}
export default function TeaSet() {
@@ -115,17 +115,17 @@ export default function TeaSet() {
-This component is reading and writing a `guest` variable declared outside of it. This means that **calling this component multiple times will produce different JSX!** And what's more, if _other_ components read `guest`, they will produce different JSX, too, depending on when they were rendered! That's not predictable.
+Este componente está lendo e escrevendo uma variável `guest` declarada fora dele. Isso significa que **chamar este componente várias vezes produzirá diferentes JSX!** E o que é mais, se _outros_ componentes lerem `guest`, eles também produzirão diferentes JSX dependendo de quando foram renderizados! Isso não é previsível.
-Going back to our formula , now even if , we cannot trust that . Our tests could fail, our users would be baffled, planes would fall out of the sky—you can see how this would lead to confusing bugs!
+Voltando à nossa fórmula , agora mesmo se , não podemos confiar que . Nossos testes podem falhar, nossos usuários ficariam perplexos, os aviões cairiam do céu — você pode ver como isso levaria a erros confusos!
-You can fix this component by [passing `guest` as a prop instead](/learn/passing-props-to-a-component):
+Você pode corrigir este componente [passando `guest` como uma prop em vez disso](/learn/passing-props-to-a-component):
```js
function Cup({ guest }) {
- return Tea cup for guest #{guest}
;
+ return Xícara de chá para o convidado #{guest}
;
}
export default function TeaSet() {
@@ -141,37 +141,37 @@ export default function TeaSet() {
-Now your component is pure, as the JSX it returns only depends on the `guest` prop.
+Agora seu componente é puro, pois o JSX que ele retorna só depende da prop `guest`.
-In general, you should not expect your components to be rendered in any particular order. It doesn't matter if you call before or after : both formulas will resolve independently of each other. In the same way, each component should only "think for itself", and not attempt to coordinate with or depend upon others during rendering. Rendering is like a school exam: each component should calculate JSX on their own!
+Em geral, você não deve esperar que seus componentes sejam renderizados em nenhuma ordem específica. Não importa se você chama antes ou depois de : ambas as fórmulas serão resolvidas independentemente uma da outra. Da mesma forma, cada componente deve apenas "pensar por si mesmo" e não tentar coordenar ou depender de outros durante a renderização. A renderização é como um exame escolar: cada componente deve calcular JSX sozinho!
-#### Detecting impure calculations with StrictMode {/*detecting-impure-calculations-with-strict-mode*/}
+#### Detectando cálculos impuros com StrictMode {/*detecting-impure-calculations-with-strict-mode*/}
-Although you might not have used them all yet, in React there are three kinds of inputs that you can read while rendering: [props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context.](/learn/passing-data-deeply-with-context) You should always treat these inputs as read-only.
+Embora você possa não ter usado todos eles ainda, no React existem três tipos de entradas que você pode ler ao renderizar: [props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory) e [context.](/learn/passing-data-deeply-with-context) Você sempre deve tratar essas entradas como somente leitura.
-When you want to *change* something in response to user input, you should [set state](/learn/state-a-components-memory) instead of writing to a variable. You should never change preexisting variables or objects while your component is rendering.
+Quando você deseja *alterar* algo em resposta à entrada do usuário, você deve [definir o state](/learn/state-a-components-memory) em vez de escrever em uma variável. Você nunca deve alterar variáveis ou objetos pré-existentes enquanto seu componente está renderizando.
-React offers a "Strict Mode" in which it calls each component's function twice during development. **By calling the component functions twice, Strict Mode helps find components that break these rules.**
+React oferece um "Modo Estrito" no qual ele chama a função de cada componente duas vezes durante o desenvolvimento. **Ao chamar as funções do componente duas vezes, o Modo Estrito ajuda a encontrar componentes que quebram essas regras.**
-Notice how the original example displayed "Guest #2", "Guest #4", and "Guest #6" instead of "Guest #1", "Guest #2", and "Guest #3". The original function was impure, so calling it twice broke it. But the fixed pure version works even if the function is called twice every time. **Pure functions only calculate, so calling them twice won't change anything**--just like calling `double(2)` twice doesn't change what's returned, and solving twice doesn't change what y is. Same inputs, same outputs. Always.
+Observe como o exemplo original exibiu "Convidado #2", "Convidado #4" e "Convidado #6" em vez de "Convidado #1", "Convidado #2" e "Convidado #3". A função original era impura, então chamá-la duas vezes a quebrou. Mas a versão pura corrigida funciona mesmo se a função for chamada duas vezes toda vez. **Funções puras apenas calculam, então chamá-las duas vezes não mudará nada** — assim como chamar `double(2)` duas vezes não altera o que é retornado, e resolver duas vezes não altera o que é y. Mesmas entradas, mesmas saídas. Sempre.
-Strict Mode has no effect in production, so it won't slow down the app for your users. To opt into Strict Mode, you can wrap your root component into ``. Some frameworks do this by default.
+O Modo Estrito não tem efeito em produção, por isso não diminuirá a velocidade do aplicativo para seus usuários. Para participar do Modo Estrito, você pode envolver seu componente raiz em ``. Algumas estruturas fazem isso por padrão.
-### Local mutation: Your component's little secret {/*local-mutation-your-components-little-secret*/}
+### Mutação local: O pequeno segredo do seu componente {/*local-mutation-your-components-little-secret*/}
-In the above example, the problem was that the component changed a *preexisting* variable while rendering. This is often called a **"mutation"** to make it sound a bit scarier. Pure functions don't mutate variables outside of the function's scope or objects that were created before the call—that makes them impure!
+No exemplo acima, o problema era que o componente alterava uma variável *pré-existente* durante a renderização. Isso geralmente é chamado de **"mutação"** para fazê-lo soar um pouco mais assustador. Funções puras não mutam variáveis fora do escopo da função ou objetos que foram criados antes da chamada — isso as torna impuras!
-However, **it's completely fine to change variables and objects that you've *just* created while rendering.** In this example, you create an `[]` array, assign it to a `cups` variable, and then `push` a dozen cups into it:
+No entanto, **é perfeitamente aceitável alterar variáveis e objetos que você acabou de *criar* durante a renderização.** Neste exemplo, você cria uma array `[]`, atribui a ela a variável `cups` e, em seguida, `push` uma dúzia de xícaras nela:
```js
function Cup({ guest }) {
- return Tea cup for guest #{guest}
;
+ return Xícara de chá para o convidado #{guest}
;
}
export default function TeaGathering() {
@@ -185,59 +185,57 @@ export default function TeaGathering() {
-If the `cups` variable or the `[]` array were created outside the `TeaGathering` function, this would be a huge problem! You would be changing a *preexisting* object by pushing items into that array.
+Se a variável `cups` ou a array `[]` fossem criadas fora da função `TeaGathering`, isso seria um grande problema! Você estaria alterando um objeto *pré-existente* inserindo itens nessa array.
-However, it's fine because you've created them *during the same render*, inside `TeaGathering`. No code outside of `TeaGathering` will ever know that this happened. This is called **"local mutation"**—it's like your component's little secret.
+No entanto, está tudo bem porque você os criou *durante a mesma renderização*, dentro de `TeaGathering`. Nenhum código fora de `TeaGathering` saberá que isso aconteceu. Isso é chamado de **"mutação local"** — é como o pequeno segredo do seu componente.
-## Where you _can_ cause side effects {/*where-you-_can_-cause-side-effects*/}
+## Onde você _pode_ causar efeitos colaterais {/*where-you-_can_-cause-side-effects*/}
-While functional programming relies heavily on purity, at some point, somewhere, _something_ has to change. That's kind of the point of programming! These changes—updating the screen, starting an animation, changing the data—are called **side effects.** They're things that happen _"on the side"_, not during rendering.
+Embora a programação funcional dependa fortemente da pureza, em algum momento, em algum lugar, _algo_ tem que mudar. Esse é o ponto da programação! Essas mudanças — atualizar a tela, iniciar uma animação, alterar os dados — são chamadas de **efeitos colaterais.** São coisas que acontecem _"à parte"_, não durante a renderização.
-In React, **side effects usually belong inside [event handlers.](/learn/responding-to-events)** Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined *inside* your component, they don't run *during* rendering! **So event handlers don't need to be pure.**
+No React, **efeitos colaterais geralmente pertencem a [manipuladores de eventos.](/learn/responding-to-events)** Os manipuladores de eventos são funções que o React executa quando você executa alguma ação — por exemplo, ao clicar em um botão. Embora os manipuladores de eventos sejam definidos *dentro* do seu componente, eles não são executados *durante* a renderização! **Portanto, os manipuladores de eventos não precisam ser puros.**
-If you've exhausted all other options and can't find the right event handler for your side effect, you can still attach it to your returned JSX with a [`useEffect`](/apis/useeffect) call in your component. This tells React to execute it later, after rendering, when side effects are allowed. **However, this approach should be your last resort.**
+Se você esgotou todas as outras opções e não consegue encontrar o manipulador de eventos certo para seu efeito colateral, você ainda pode anexá-lo ao seu JSX retornado com uma chamada [`useEffect`](/apis/useeffect) em seu componente. Isso diz ao React para executá-lo mais tarde, após a renderização, quando os efeitos colaterais são permitidos. **No entanto, essa abordagem deve ser seu último recurso.**
-When possible, try to express your logic with rendering alone. You'll be surprised how far this can take you!
+Quando possível, tente expressar sua lógica apenas com a renderização. Você ficará surpreso com o quão longe isso pode te levar!
-#### Why does React care about purity? {/*why-does-react-care-about-purity*/}
+#### Por que o React se importa com a pureza? {/*why-does-react-care-about-purity*/}
-Writing pure functions takes some habit and discipline. But it also unlocks marvelous opportunities:
+Escrever funções puras requer um certo hábito e disciplina. Mas também abre oportunidades maravilhosas:
-* Your components could run in a different environment—for example, on the server! Since they return the same result for the same inputs, one component can serve many user requests.
-* You can improve performance by [skipping rendering](/reference/react/memo) components whose inputs have not changed. This is safe because pure functions always return the same results, so they are safe to cache.
-* If some data changes in the middle of rendering a deep component tree, React can restart rendering without wasting time to finish the outdated render. Purity makes it safe to stop calculating at any time.
+* Seus componentes podem ser executados em um ambiente diferente — por exemplo, no servidor! Como eles retornam o mesmo resultado para as mesmas entradas, um componente pode atender a muitas solicitações de usuários.
+* Você pode melhorar o desempenho [ignorando a renderização](/reference/react/memo) de componentes cujas entradas não foram alteradas. Isso é seguro porque as funções puras sempre retornam os mesmos resultados, por isso são seguras para cache.
+* Se alguns dados forem alterados no meio da renderização de uma árvore de componentes profunda, o React pode reiniciar a renderização sem perder tempo para terminar a renderização desatualizada. A pureza torna seguro parar de calcular a qualquer momento.
-Every new React feature we're building takes advantage of purity. From data fetching to animations to performance, keeping components pure unlocks the power of the React paradigm.
+Cada novo recurso do React que estamos construindo tira proveito da pureza. Da obtenção de dados a animações e desempenho, manter os componentes puros desbloqueia o poder do paradigma React.
-* A component must be pure, meaning:
- * **It minds its own business.** It should not change any objects or variables that existed before rendering.
- * **Same inputs, same output.** Given the same inputs, a component should always return the same JSX.
-* Rendering can happen at any time, so components should not depend on each others' rendering sequence.
-* You should not mutate any of the inputs that your components use for rendering. That includes props, state, and context. To update the screen, ["set" state](/learn/state-a-components-memory) instead of mutating preexisting objects.
-* Strive to express your component's logic in the JSX you return. When you need to "change things", you'll usually want to do it in an event handler. As a last resort, you can `useEffect`.
-* Writing pure functions takes a bit of practice, but it unlocks the power of React's paradigm.
+* Um componente deve ser puro, o que significa:
+ * **Ele cuida de seus próprios negócios.** Ele não deve alterar nenhum objeto ou variável que existia antes da renderização.
+ * **Mesmas entradas, mesma saída.** Dadas as mesmas entradas, um componente deve sempre retornar o mesmo JSX.
+* A renderização pode acontecer a qualquer momento, portanto, os componentes não devem depender da sequência de renderização uns dos outros.
+* Você não deve mutar nenhuma das entradas que seus componentes usam para renderização. Isso inclui props, state e context. Para atualizar a tela, ["defina" o state](/learn/state-a-components-memory) em vez de mutar objetos pré-existentes.
+* Esforce-se para expressar a lógica do seu componente no JSX que você retorna. Quando você precisar "mudar as coisas", geralmente vai querer fazê-lo em um manipulador de eventos. Como último recurso, você pode usar `useEffect`.
+* Escrever funções puras leva um pouco de prática, mas desbloqueia o poder do paradigma do React.
-
-
-#### Fix a broken clock {/*fix-a-broken-clock*/}
+#### Consertar um relógio quebrado {/*fix-a-broken-clock*/}
-This component tries to set the ``'s CSS class to `"night"` during the time from midnight to six hours in the morning, and `"day"` at all other times. However, it doesn't work. Can you fix this component?
+Este componente tenta definir a classe CSS do `` para `"night"` durante o horário da meia-noite às seis da manhã e `"day"` em todos os outros horários. No entanto, não funciona. Você pode consertar este componente?
-You can verify whether your solution works by temporarily changing the computer's timezone. When the current time is between midnight and six in the morning, the clock should have inverted colors!
+Você pode verificar se sua solução funciona alterando temporariamente o fuso horário do computador. Quando a hora atual estiver entre meia-noite e seis da manhã, o relógio deve ter cores invertidas!
-Rendering is a *calculation*, it shouldn't try to "do" things. Can you express the same idea differently?
+Renderização é um *cálculo*, não deve tentar "fazer" coisas. Você pode expressar a mesma ideia de forma diferente?
@@ -301,7 +299,7 @@ body > * {
-You can fix this component by calculating the `className` and including it in the render output:
+Você pode consertar este componente calculando o `className` e incluindo-o na saída de renderização:
@@ -362,19 +360,19 @@ body > * {
-In this example, the side effect (modifying the DOM) was not necessary at all. You only needed to return JSX.
+Neste exemplo, o efeito colateral (modificar o DOM) não era necessário. Você só precisava retornar JSX.
-#### Fix a broken profile {/*fix-a-broken-profile*/}
+#### Consertar um perfil quebrado {/*fix-a-broken-profile*/}
-Two `Profile` components are rendered side by side with different data. Press "Collapse" on the first profile, and then "Expand" it. You'll notice that both profiles now show the same person. This is a bug.
+Dois componentes `Profile` são renderizados lado a lado com dados diferentes. Pressione "Collapse" no primeiro perfil e, em seguida, "Expand" nele. Você notará que ambos os perfis agora mostram a mesma pessoa. Este é um erro.
-Find the cause of the bug and fix it.
+Encontre a causa do erro e corrija-o.
-The buggy code is in `Profile.js`. Make sure you read it all from top to bottom!
+O código com erro está em `Profile.js`. Certifique-se de ler tudo do início ao fim!
@@ -475,9 +473,9 @@ h1 { margin: 5px; font-size: 18px; }
-The problem is that the `Profile` component writes to a preexisting variable called `currentPerson`, and the `Header` and `Avatar` components read from it. This makes *all three of them* impure and difficult to predict.
+O problema é que o componente `Profile` grava em uma variável pré-existente chamada `currentPerson`, e os componentes `Header` e `Avatar` leem dela. Isso torna *todos os três* impuros e difíceis de prever.
-To fix the bug, remove the `currentPerson` variable. Instead, pass all information from `Profile` to `Header` and `Avatar` via props. You'll need to add a `person` prop to both components and pass it all the way down.
+Para corrigir o erro, remova a variável `currentPerson`. Em vez disso, passe todas as informações de `Profile` para `Header` e `Avatar` via props. Você precisará adicionar uma prop `person` a ambos os componentes e passá-la até o fim.
@@ -571,15 +569,15 @@ h1 { margin: 5px; font-size: 18px; }
-Remember that React does not guarantee that component functions will execute in any particular order, so you can't communicate between them by setting variables. All communication must happen through props.
+Lembre-se de que o React não garante que as funções do componente serão executadas em nenhuma ordem específica, portanto, você não pode se comunicar entre elas definindo variáveis. Toda comunicação deve acontecer por meio de props.
-#### Fix a broken story tray {/*fix-a-broken-story-tray*/}
+#### Conserte uma bandeja de histórias quebrada {/*fix-a-broken-story-tray*/}
-The CEO of your company is asking you to add "stories" to your online clock app, and you can't say no. You've written a `StoryTray` component that accepts a list of `stories`, followed by a "Create Story" placeholder.
+O CEO da sua empresa está pedindo que você adicione "histórias" ao seu aplicativo de relógio online, e você não pode dizer não. Você escreveu um componente `StoryTray` que aceita uma lista de `stories`, seguido de um espaço reservado "Criar História".
-You implemented the "Create Story" placeholder by pushing one more fake story at the end of the `stories` array that you receive as a prop. But for some reason, "Create Story" appears more than once. Fix the issue.
+Você implementou o espaço reservado "Criar História" inserindo mais uma história falsa no final da array `stories` que você recebe como uma prop. Mas, por algum motivo, "Criar História" aparece mais de uma vez. Corrija o problema.
@@ -615,8 +613,8 @@ export default function App() {
let [stories, setStories] = useState([...initialStories])
let time = useTime();
- // HACK: Prevent the memory from growing forever while you read docs.
- // We're breaking our own rules here.
+ // HACK: Impedir que a memória cresça para sempre enquanto você lê a documentação.
+ // Estamos quebrando nossas próprias regras aqui.
if (stories.length > 100) {
stories.length = 100;
}
@@ -629,7 +627,7 @@ export default function App() {
textAlign: 'center',
}}
>
- It is {time.toLocaleTimeString()} now.
+ Agora são {time.toLocaleTimeString()}.
);
@@ -675,11 +673,11 @@ li {
-Notice how whenever the clock updates, "Create Story" is added *twice*. This serves as a hint that we have a mutation during rendering--Strict Mode calls components twice to make these issues more noticeable.
+Observe como, sempre que o relógio é atualizado, "Criar História" é adicionado *duas vezes*. Isso serve como uma dica de que temos uma mutação durante a renderização — o Modo Estrito chama os componentes duas vezes para tornar esses problemas mais perceptíveis.
-`StoryTray` function is not pure. By calling `push` on the received `stories` array (a prop!), it is mutating an object that was created *before* `StoryTray` started rendering. This makes it buggy and very difficult to predict.
+A função `StoryTray` não é pura. Ao chamar `push` na array `stories` recebida (uma prop!), ela está mutando um objeto que foi criado *antes* que `StoryTray` começasse a renderizar. Isso o torna com erros e muito difícil de prever.
-The simplest fix is to not touch the array at all, and render "Create Story" separately:
+A correção mais simples é não tocar na array e renderizar "Criar História" separadamente:
@@ -692,7 +690,7 @@ export default function StoryTray({ stories }) {
{story.label}
))}
- Create Story
+ Criar História
);
}
@@ -711,8 +709,8 @@ export default function App() {
let [stories, setStories] = useState([...initialStories])
let time = useTime();
- // HACK: Prevent the memory from growing forever while you read docs.
- // We're breaking our own rules here.
+ // HACK: Impedir que a memória cresça para sempre enquanto você lê a documentação.
+ // Estamos quebrando nossas próprias regras aqui.
if (stories.length > 100) {
stories.length = 100;
}
@@ -725,7 +723,7 @@ export default function App() {
textAlign: 'center',
}}
>
- It is {time.toLocaleTimeString()} now.
+ Agora são {time.toLocaleTimeString()}.
);
@@ -763,16 +761,16 @@ li {
-Alternatively, you could create a _new_ array (by copying the existing one) before you push an item into it:
+Alternativamente, você pode criar uma _nova_ array (copiando a existente) antes de inserir um item nela:
```js src/StoryTray.js active
export default function StoryTray({ stories }) {
- // Copy the array!
+ // Copiar a array!
let storiesToDisplay = stories.slice();
- // Does not affect the original array:
+ // Não afeta a array original:
storiesToDisplay.push({
id: 'create',
label: 'Create Story'
@@ -803,8 +801,8 @@ export default function App() {
let [stories, setStories] = useState([...initialStories])
let time = useTime();
- // HACK: Prevent the memory from growing forever while you read docs.
- // We're breaking our own rules here.
+ // HACK: Impedir que a memória cresça para sempre enquanto você lê a documentação.
+ // Estamos quebrando nossas próprias regras aqui.
if (stories.length > 100) {
stories.length = 100;
}
@@ -817,7 +815,7 @@ export default function App() {
textAlign: 'center',
}}
>
- It is {time.toLocaleTimeString()} now.
+ Agora são {time.toLocaleTimeString()}.
);
@@ -855,10 +853,10 @@ li {
-This keeps your mutation local and your rendering function pure. However, you still need to be careful: for example, if you tried to change any of the array's existing items, you'd have to clone those items too.
+Isso mantém sua mutação local e sua função de renderização pura. No entanto, você ainda precisa ter cuidado: por exemplo, se você tentasse alterar algum dos itens existentes da array, você também teria que clonar esses itens.
-It is useful to remember which operations on arrays mutate them, and which don't. For example, `push`, `pop`, `reverse`, and `sort` will mutate the original array, but `slice`, `filter`, and `map` will create a new one.
+É útil lembrar quais operações em arrays as mutam e quais não. Por exemplo, `push`, `pop`, `reverse` e `sort` mutarão a array original, mas `slice`, `filter` e `map` criarão uma nova.
-
+
\ No newline at end of file