diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index d35071845..b55de6eff 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -1,28 +1,28 @@ --- -title: Preserving and Resetting State +title: Preservando e Reinicializando o Estado --- -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. +O estado é isolado entre os componentes. O React controla qual estado pertence a qual componente com base em sua posição na árvore da UI. Você pode controlar quando preservar o estado e quando reiniciá-lo entre renderizações. -* 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 o React escolhe preservar ou reiniciar o estado +* Como forçar o React a reiniciar o estado do componente +* Como chaves e tipos afetam se o estado é preservado -## State is tied to a position in the render tree {/*state-is-tied-to-a-position-in-the-tree*/} +## O estado está associado a uma posição na árvore de renderização {/*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. +O React constrói [árvores de renderização](learn/understanding-your-ui-as-a-tree#the-render-tree) para a estrutura do componente em sua 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 você dá um estado a um componente, pode pensar que o estado "vive" dentro do componente. Mas o estado é, na verdade, mantido dentro do React. O React associa cada parte do estado que está armazenando com o componente correto pela posição em que esse componente se encontra na árvore de renderização. -Here, there is only one `` JSX tag, but it's rendered at two different positions: +Aqui, há apenas uma tag JSX ``, mas ela é renderizada em duas posições diferentes: @@ -56,7 +56,7 @@ function Counter() { >

{score}

); @@ -86,23 +86,23 @@ label {
-Here's how these look as a tree: +Veja como isso fica como uma árvore: - + -React tree +Árvore 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. +**Esses são dois contadores separados porque cada um é renderizado em sua própria posição na árvore.** Normalmente, você não precisa pensar sobre essas posições ao usar o React, mas pode ser útil entender como funciona. -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. +No React, cada componente na tela tem estado totalmente isolado. Por exemplo, se você renderizar dois componentes `Counter` lado a lado, cada um deles terá seus próprios estados `score` e `hover`, independentes. -Try clicking both counters and notice they don't affect each other: +Tente clicar em ambos os contadores e perceba que eles não afetam um ao outro: @@ -135,7 +135,7 @@ function Counter() { >

{score}

); @@ -160,21 +160,21 @@ function Counter() {
-As you can see, when one counter is updated, only the state for that component is updated: +Como você pode ver, quando um contador é atualizado, apenas o estado daquele componente é atualizado: - + -Updating state +Atualizando estado -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: +O React manterá o estado enquanto você renderizar o mesmo componente na mesma posição na árvore. Para ver isso, incremente ambos os contadores, em seguida, remova o segundo componente desmarcando a caixa "Renderizar o segundo contador" e, em seguida, adicione-o novamente marcando-a: @@ -195,7 +195,7 @@ export default function App() { setShowB(e.target.checked) }} /> - Render the second counter + Renderizar o segundo contador ); @@ -218,7 +218,7 @@ function Counter() { >

{score}

); @@ -248,35 +248,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. +Perceba como no momento em que você para de renderizar o segundo contador, seu estado desaparece completamente. Isso ocorre porque quando o React remove um componente, ele destrói seu estado. - + -Deleting a component +Deletando um 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 você marca "Renderizar o segundo contador", um segundo `Counter` e seu estado são inicializados do zero (`score = 0`) e adicionados ao DOM. - + -Adding a component +Adicionando um 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. +**O React preserva o estado de um componente enquanto ele é renderizado em sua posição na árvore da UI.** Se ele for removido, ou um componente diferente for renderizado na mesma posição, o React descarta seu estado. -## Same component at the same position preserves state {/*same-component-at-the-same-position-preserves-state*/} +## O mesmo componente na mesma posição preserva o estado {/*same-component-at-the-same-position-preserves-state*/} -In this example, there are two different `` tags: +Neste exemplo, há duas tags `` diferentes: @@ -300,7 +300,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usar estilo elegante ); @@ -326,7 +326,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -361,24 +361,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 você marca ou desmarca a caixa de seleção, o estado do contador não é reinicializado. Se `isFancy` for `true` ou `false`, você sempre terá um `` como primeiro filho do componente raiz `App`: - + -Updating the `App` state does not reset the `Counter` because `Counter` stays in the same position +Atualizando o estado do `App` não reinicializa o `Counter` porque `Counter` permanece na mesma posição -It's the same component at the same position, so from React's perspective, it's the same counter. +É o mesmo componente na mesma posição, então do ponto de vista do React, é o mesmo contador. -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`: +Lembre-se de que **é a posição na árvore da UI--não na marcação JSX--que importa para o React!** Este componente tem duas cláusulas `return` com diferentes tags JSX `` dentro e fora do `if`: @@ -399,7 +399,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usar estilo elegante ); @@ -415,7 +415,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usar estilo elegante ); @@ -441,7 +441,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -476,15 +476,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. +Você pode esperar que o estado seja reinicializado ao marcar a caixa, mas não é! Isso acontece porque **ambas as tags `` são renderizadas na mesma posição.** O React não sabe onde você coloca as condições em sua função. Tudo o que ele "vê" é a árvore que você retorna. -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. +Em ambos os casos, o componente `App` retorna uma `
` com `` como primeiro filho. Para o React, esses dois contadores têm o mesmo "endereço": o primeiro filho do primeiro filho da raiz. É assim que o React os compara entre as renderizações anterior e seguinte, independentemente de como você estrutura sua lógica. -## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/} +## Componentes diferentes na mesma posição reinicializam o estado {/*different-components-at-the-same-position-reset-state*/} -In this example, ticking the checkbox will replace `` with a `

`: +Neste exemplo, ao marcar a caixa de seleção, você substituirá `` por um `

`: @@ -496,7 +496,7 @@ export default function App() { return (

{isPaused ? ( -

See you later!

+

Até mais!

) : ( )} @@ -508,7 +508,7 @@ export default function App() { setIsPaused(e.target.checked) }} /> - Take a break + Fazer uma pausa
); @@ -531,7 +531,7 @@ function Counter() { >

{score}

); @@ -561,13 +561,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. +Aqui, você alterna entre tipos de componentes _diferentes_ na mesma posição. Inicialmente, o primeiro filho da `
` continha um `Counter`. Mas quando você trocou por um `p`, o React removeu o `Counter` da árvore da UI e destruiu seu estado. - + -When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added +Quando `Counter` muda para `p`, o `Counter` é deletado e o `p` é adicionado @@ -575,15 +575,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 você alterna de volta, o `p` é deletado e o `Counter` é adicionado -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: +Além disso, **quando você renderiza um componente diferente na mesma posição, isso reinicializa o estado de toda a sua subárvore.** Para ver como isso funciona, incremente o contador e, em seguida, marque a caixa de seleção: @@ -611,7 +611,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usar estilo elegante
); @@ -637,7 +637,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -672,13 +672,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 `div` to a `section`. When the child `div` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well. +O estado do contador é reinicializado quando você clica na caixa de seleção. Embora você renderize um `Counter`, o primeiro filho da `div` muda de `div` para `section`. Quando o filho `div` foi removido do DOM, toda a árvore abaixo dele (incluindo o `Counter` e seu estado) também foi destruída. - + -When `section` changes to `div`, the `section` is deleted and the new `div` is added +Quando 'section' muda para 'div', a 'section' é deletada e o novo 'div' é adicionado @@ -686,21 +686,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 alterna de volta, o 'div' é deletado e a nova 'section' é adicionada -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. +Como regra geral, **se você quiser preservar o estado entre renderizações, a estrutura da sua árvore precisa "combinar" de uma renderização para outra.** Se a estrutura for diferente, o estado é destruído porque o React destrói o estado quando remove um componente da árvore. -This is why you should not nest component function definitions. +Esse é o motivo pelo qual você não deve aninhar definições de funções de componentes. -Here, the `MyTextField` component function is defined *inside* `MyComponent`: +Aqui, a função de componente `MyTextField` é definida *dentro* de `MyComponent`: @@ -726,7 +726,7 @@ export default function MyComponent() { + }}>Clicado {counter} vezes ); } @@ -735,13 +735,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.** +Toda vez que você clica no botão, o estado de entrada desaparece! Isso acontece porque uma *nova* função `MyTextField` é criada a cada renderização de `MyComponent`. Você está renderizando um *componente diferente* na mesma posição, então o React reinicializa todo o estado abaixo disso. Isso leva a bugs e problemas de desempenho. Para evitar esse problema, **declare sempre funções de componentes no nível superior e não aninhe suas definições.** -## Resetting state at the same position {/*resetting-state-at-the-same-position*/} +## Reinicializando o estado na mesma posição {/*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: +Por padrão, o React preserva o estado de um componente enquanto ele permanece na mesma posição. Normalmente, isso é exatamente o que você deseja, então faz sentido como o comportamento padrão. Mas às vezes, você pode querer reinicializar o estado de um componente. Considere este aplicativo que permite que dois jogadores mantenham o controle de suas pontuações durante cada turno: @@ -760,7 +760,7 @@ export default function Scoreboard() {
); @@ -783,7 +783,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -811,19 +811,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. +Atualmente, quando você muda de jogador, a pontuação é preservada. Os dois `Counter`s aparecem na mesma posição, então o React os vê como *o mesmo* `Counter` cujo prop `person` mudou. -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. +Mas, conceitualmente, neste aplicativo, eles deveriam ser dois contadores separados. Eles podem aparecer no mesmo lugar na UI, mas um é um contador para Taylor e outro é um contador para Sarah. -There are two ways to reset state when switching between them: +Existem duas maneiras de reinicializar o estado ao alternar entre eles: -1. Render components in different positions -2. Give each component an explicit identity with `key` +1. Renderizar componentes em posições diferentes +2. Dar a cada componente uma identidade explícita com `key` -### Option 1: Rendering a component in different positions {/*option-1-rendering-a-component-in-different-positions*/} +### Opção 1: Renderizando um componente em posições diferentes {/*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 você quer que esses dois `Counter`s sejam independentes, pode renderizá-los em duas posições diferentes: @@ -843,7 +843,7 @@ export default function Scoreboard() { ); @@ -866,7 +866,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -894,42 +894,50 @@ 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`. +* Inicialmente, `isPlayerA` é `true`. Assim, a primeira posição contém o estado do `Counter`, e a segunda está vazia. +* Quando você clica no botão "Próximo jogador", a primeira posição é limpa, mas a segunda agora contém um `Counter`. - + -Initial state +Estado inicial - + + + -Clicking "next" + + +Clicando em "próximo" - + + + + + -Clicking "next" again +Clicando em "próximo" novamente -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. +Cada estado do `Counter` é destruído toda vez que ele é removido do DOM. Essa é a razão pela qual eles são reinicializados toda vez que você clica no botão. -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. +Essa solução é conveniente quando você tem apenas alguns componentes independentes renderizados no mesmo lugar. Neste exemplo, você tem apenas dois, então não é um problema renderizá-los separadamente no JSX. -### Option 2: Resetting state with a key {/*option-2-resetting-state-with-a-key*/} +### Opção 2: Reinicializando o estado com uma chave {/*option-2-resetting-state-with-a-key*/} -There is also another, more generic, way to reset a component's state. +Há também outra maneira mais genérica de reinicializar o estado de um 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! +Você pode ter visto `keys` ao [renderizar listas.](/learn/rendering-lists#keeping-list-items-in-order-with-key) As chaves não são apenas para listas! Você pode usar chaves para fazer o React distinguir entre quaisquer componentes. Por padrão, o React usa a ordem dentro do pai ("primeiro contador", "segundo contador") para discernir entre os componentes. Mas as chaves permitem que você diga ao React que este não é apenas um *primeiro* contador, ou um *segundo* contador, mas um contador específico--por exemplo, o contador *de Taylor*. Dessa forma, o React saberá qual é o contador *de Taylor* onde quer que apareça na árvore! -In this example, the two ``s don't share state even though they appear in the same place in JSX: +Neste exemplo, os dois `` não compartilham estado, mesmo que apareçam no mesmo lugar no JSX: @@ -948,7 +956,7 @@ export default function Scoreboard() { ); @@ -971,7 +979,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -999,7 +1007,7 @@ h1 {
-Switching between Taylor and Sarah does not preserve the state. This is because **you gave them different `key`s:** +Alternar entre Taylor e Sarah não preserva o estado. Isso acontece porque **você deu a eles `key`s diferentes:** ```js {isPlayerA ? ( @@ -1009,19 +1017,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. +Especificar uma `key` diz ao React para usar a `key` em si como parte da posição, em vez de sua ordem dentro do pai. É por isso que, mesmo que você os renderize no mesmo lugar no JSX, o React os vê como dois contadores diferentes, e assim eles nunca compartilharão estado. Cada vez que um contador aparece na tela, seu estado é criado. Cada vez que é removido, seu estado é destruído. Alternar entre eles reinicializa seu estado repetidamente. -Remember that keys are not globally unique. They only specify the position *within the parent*. +Lembre-se de que as chaves não são globalmente únicas. Elas apenas especificam a posição *dentro do pai*. -### Resetting a form with a key {/*resetting-a-form-with-a-key*/} +### Reinicializando um formulário com uma chave {/*resetting-a-form-with-a-key*/} -Resetting state with a key is particularly useful when dealing with forms. +Reinicializar o estado com uma chave é particularmente útil quando se trata de formulários. -In this chat app, the `` component contains the text input state: +Neste aplicativo de chat, o componente `` contém o estado da entrada de texto: @@ -1084,11 +1092,11 @@ export default function Chat({ contact }) {