Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finish translation of Choosing the State Structure #582

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

undead404
Copy link
Contributor

No description provided.

Copy link

vercel bot commented Dec 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
uk-legacy-reactjs-org ⬜️ Ignored (Inspect) Visit Preview Dec 29, 2024 8:34pm

Copy link

Size changes

📦 Next.js Bundle Analysis for react-dev

This analysis was generated by the Next.js Bundle Analysis action. 🤖

Five Pages Changed Size

The following pages changed size from the code in this PR compared to its base branch:

Page Size (compressed) First Load
/404 106.41 KB (🟡 +6 B) 210.79 KB
/500 106.41 KB (🟡 +6 B) 210.79 KB
/[[...markdownPath]] 108.32 KB (🟡 +6 B) 212.7 KB
/errors 106.62 KB (🟡 +6 B) 211 KB
/errors/[errorCode] 106.6 KB (🟡 +6 B) 210.98 KB
Details

Only the gzipped size is provided here based on an expert tip.

First Load is the size of the global bundle plus the bundle for the individual page. If a user were to show up to your website and land on a given page, the first load size represents the amount of javascript that user would need to download. If next/link is used, subsequent page loads would only need to download that page's bundle (the number in the "Size" column), since the global bundle has already been downloaded.

Any third party scripts you have added directly to your app using the <script> tag are not accounted for in this analysis

Next to the size is how much the size has increased or decreased compared with the base branch of this PR. If this percentage has increased by 10% or more, there will be a red status indicator applied, indicating that special attention should be given to this.

Copy link
Collaborator

@alinkedd alinkedd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Перша частина перевірки (тільки приклади)

childPlaces: []
}, {
id: 24,
title: 'Thailand',
title: 'Тайланд',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
title: 'Тайланд',
title: 'Таїланд',

childIds: []
},
24: {
id: 24,
title: 'Thailand',
title: 'Тайланд',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
title: 'Тайланд',
title: 'Таїланд',

childIds: []
},
24: {
id: 24,
title: 'Thailand',
title: 'Тайланд',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
title: 'Тайланд',
title: 'Таїланд',

childIds: []
},
24: {
id: 24,
title: 'Thailand',
title: 'Тайланд',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
title: 'Тайланд',
title: 'Таїланд',

@@ -599,7 +599,7 @@ export default function TravelPlan() {
const planets = plan.childPlaces;
return (
<>
<h2>Places to visit</h2>
<h2>Місця, варті відвідування</h2>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можливо, краще зробити або без коми, або переробити, або додати які

Suggested change
<h2>Місця, варті відвідування</h2>
<h2>Місця для відвідування</h2>
Suggested change
<h2>Місця, варті відвідування</h2>
<h2>Що б відвідати</h2>
Suggested change
<h2>Місця, варті відвідування</h2>
<h2>Що відвідати</h2>
Suggested change
<h2>Місця, варті відвідування</h2>
<h2>Що варто відвідати</h2>
Suggested change
<h2>Місця, варті відвідування</h2>
<h2>Місця, що варті відвідування</h2>

@@ -2548,7 +2548,7 @@ export default function MailClient() {
<hr />
<p>
<b>
You selected {selectedCount} letters
Ви обрали {selectedCount} листів
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можливо, краще якийсь варіант, щоби число не узгоджувати?

Suggested change
Ви обрали {selectedCount} листів
Ви обрали листи: {selectedCount}

Чи якось так.

Не хочеться дивитися на "Ви обрали 1 листів" :)

@@ -2624,14 +2624,14 @@ export default function MailClient() {
const selectedCount = selectedIds.length;

function handleToggle(toggledId) {
// Was it previously selected?
// Чи був цей лист досі обраним?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Чи був цей лист досі обраним?
// Чи був цей лист обраним перед цим?

або якось так, досі тут погано зчитується

if (selectedIds.includes(toggledId)) {
// Then remove this ID from the array.
// Тоді вилучіть цей ідентифікатор з масиву.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Тоді вилучіть цей ідентифікатор з масиву.
// Тоді вилучіть цей ідентифікатор із масиву.

setSelectedIds(selectedIds.filter(id =>
id !== toggledId
));
} else {
// Otherwise, add this ID to the array.
// Інакше – додайте цей ідентифікатор до масиву.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Інакше додайте цей ідентифікатор до масиву.
// Інакше додайте цей ідентифікатор до масиву.

@@ -2734,7 +2734,7 @@ export default function MailClient() {
const selectedCount = selectedIds.size;

function handleToggle(toggledId) {
// Create a copy (to avoid mutation).
// Створити копію (для запобігання внесенню змін).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Створити копію (для запобігання внесенню змін).
// Створити копію (для запобігання мутаціям).


This menu list component lets you choose a single travel snack out of several:
Цей компонент списку меню дає змогу обрати один дорожній перекус з кількох:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Усі обрати/обрали замінити на вибрати/...

Обирають на посаду

Copy link
Collaborator

@alinkedd alinkedd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Друга частина перевірки (загальні зміни + текст до 226 рядка)

Третя частина перевірки буде після виправлень першої і другої частин

---

<Intro>

Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. Here are some tips you should consider when structuring state.
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати та зневаджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати при структуруванні стану.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати та зневаджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати при структуруванні стану.
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати або налагоджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати під час структурування стану.

* What to avoid when organizing state
* How to fix common issues with the state structure
* Коли використовувати одну змінну стану, а коли – декілька
* Чого слід уникати при організації стану
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* Чого слід уникати при організації стану
* Чого слід уникати під час організації стану

* When to use a single vs multiple state variables
* What to avoid when organizing state
* How to fix common issues with the state structure
* Коли використовувати одну змінну стану, а коли – декілька
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* Коли використовувати одну змінну стану, а коли декілька
* Коли використовувати одну змінну стану, а коли декілька


The goal behind these principles is to *make state easy to update without introducing mistakes*. Removing redundant and duplicate data from state helps ensure that all its pieces stay in sync. This is similar to how a database engineer might want to ["normalize" the database structure](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description) to reduce the chance of bugs. To paraphrase Albert Einstein, **"Make your state as simple as it can be--but no simpler."**
Мета цих принципів – *щоб стан було легко оновлювати без додавання помилок*. Вилучення зі стану надлишкових і продубльованих даних допомагає пересвідчитися, що всі частини синхронізовані одна з одною. Це схоже на те, як інженер баз даних міг би ["нормалізуватИ" структуру бази даних](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description), щоб знизити шанс появи дефектів. Перефразовуючи Альберта Ейнштейна, **"Роби свій стан простим, як можливо, – але не простіше цього."**
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Мета цих принципів *щоб стан було легко оновлювати без додавання помилок*. Вилучення зі стану надлишкових і продубльованих даних допомагає пересвідчитися, що всі частини синхронізовані одна з одною. Це схоже на те, як інженер баз даних міг би ["нормалізуватИ" структуру бази даних](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description), щоб знизити шанс появи дефектів. Перефразовуючи Альберта Ейнштейна, **"Роби свій стан простим, як можливо, але не простіше цього."**
Мета цих принципів *легке оновлення стану без додавання помилок*. Вилучення зі стану надлишкових і продубльованих даних допомагає пересвідчитися, що всі частини синхронізовані одна з одною. Це схоже на те, як інженер баз даних міг би ["нормалізуватИ" структуру бази даних](https://docs.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description), щоб знизити ймовірність появи дефектів. Перефразуємо Альберта Ейнштейна: **"Робіть стан настільки простим, наскільки це можливо, але не простіше цього."**

@@ -93,17 +93,17 @@ body { margin: 0; padding: 0; height: 250px; }

</Sandpack>

Another case where you'll group data into an object or an array is when you don't know how many pieces of state you'll need. For example, it's helpful when you have a form where the user can add custom fields.
Ще одна ситуація, коли дані групують в об'єкт чи масив, – це коли невідомо, скільки порцій стану знадобиться. Наприклад, це допомагає, коли є форма, куди користувач може додати власні поля.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Ще одна ситуація, коли дані групують в об'єкт чи масив, це коли невідомо, скільки порцій стану знадобиться. Наприклад, це допомагає, коли є форма, куди користувач може додати власні поля.
Ще одна ситуація, коли дані групують в об'єкт чи масив, це коли невідомо, яка частина стану знадобиться. Наприклад, це допомагає, коли є форма, в якій користувач може додавати власні поля.

@@ -2391,9 +2391,9 @@ li { border-radius: 5px; }

<Solution>

The problem is that you're holding the letter object in `highlightedLetter`. But you're also holding the same information in the `letters` array. So your state has duplication! When you update the `letters` array after the button click, you create a new letter object which is different from `highlightedLetter`. This is why `highlightedLetter === letter` check becomes `false`, and the highlight disappears. It reappears the next time you call `setHighlightedLetter` when the pointer moves.
Проблема в тому, що об'єкт листа зберігається в `highlightedLetter`. Але та сама інформація також зберігається в масиві `letters`. Тож у стані є дублювання! Коли масив `letters` оновлюється після клацання миші, створюється новий об'єкт листа, відмінний від `highlightedLetter`. Саме тому перевірка `highlightedLetter === letter` стає `false`, і виділення зникає. Воно з'являється, коли при руханні курсором знову викликається `setHighlightedLetter`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Проблема в тому, що об'єкт листа зберігається в `highlightedLetter`. Але та сама інформація також зберігається в масиві `letters`. Тож у стані є дублювання! Коли масив `letters` оновлюється після клацання миші, створюється новий об'єкт листа, відмінний від `highlightedLetter`. Саме тому перевірка `highlightedLetter === letter` стає `false`, і виділення зникає. Воно з'являється, коли при руханні курсором знову викликається `setHighlightedLetter`.
Проблема в тому, що об'єкт листа зберігається в `highlightedLetter`. Але та сама інформація також зберігається в масиві `letters`. Тож у стані є дублювання! Коли масив `letters` оновлюється після клацання миші, створюється новий об'єкт листа, відмінний від `highlightedLetter`. Саме тому перевірка `highlightedLetter === letter` стає `false`, і виділення зникає. Воно з'являється, коли після руху курсором знову викликається `setHighlightedLetter`.


```js
const [position, setPosition] = useState({ x: 0, y: 0 });
```

Technically, you can use either of these approaches. But **if some two state variables always change together, it might be a good idea to unify them into a single state variable.** Then you won't forget to always keep them in sync, like in this example where moving the cursor updates both coordinates of the red dot:
Технічно можна зробити і так, і так. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете завжди підтримувати їхню синхронізацію, як у цьому прикладі, де рухання курсора оновлює обидві координати червоної крапки:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Технічно можна зробити і так, і так. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете завжди підтримувати їхню синхронізацію, як у цьому прикладі, де рухання курсора оновлює обидві координати червоної крапки:
Технічно можна зробити і перше, і друге. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете повсякчас підтримувати їхню синхронізацію, як у цьому прикладі, де рух курсора оновлює обидві координати червоної крапки:

тавтології


<Pitfall>

If your state variable is an object, remember that [you can't update only one field in it](/learn/updating-objects-in-state) without explicitly copying the other fields. For example, you can't do `setPosition({ x: 100 })` in the above example because it would not have the `y` property at all! Instead, if you wanted to set `x` alone, you would either do `setPosition({ ...position, x: 100 })`, or split them into two state variables and do `setX(100)`.
Якщо ваша змінна стану є об'єктом, пам'ятайте, що [не можна оновлювати лише одне поле в цьому об'єкті](/learn/updating-objects-in-state), явно не скопіювавши інші поля. Наприклад, у прикладі вище не можна зробити `setPosition({ x: 100 })`, тому що тоді властивості `y` не було б узагалі! Замість цього, щоб оновити лише `x`, треба або виконати `setPosition({ ...position, x: 100 })`, або розбити змінну на дві й виконати `setX(100)`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Якщо ваша змінна стану є об'єктом, пам'ятайте, що [не можна оновлювати лише одне поле в цьому об'єкті](/learn/updating-objects-in-state), явно не скопіювавши інші поля. Наприклад, у прикладі вище не можна зробити `setPosition({ x: 100 })`, тому що тоді властивості `y` не було б узагалі! Замість цього, щоб оновити лише `x`, треба або виконати `setPosition({ ...position, x: 100 })`, або розбити змінну на дві й виконати `setX(100)`.
Якщо ваша змінна стану є об'єктом, пам'ятайте, що [не можна оновлювати лише одне поле в цьому об'єкті](/learn/updating-objects-in-state), явно не скопіювавши інші поля. Наприклад, у прикладі вище не можна зробити `setPosition({ x: 100 })`, тому що тоді властивості `y` не було б узагалі! Натомість, щоб оновити лише `x`, треба або виконати `setPosition({ ...position, x: 100 })`, або розбити змінну на дві й виконати `setX(100)`.

https://onlinecorrector.com.ua/%D0%BD%D0%B0%D1%82%D0%BE%D0%BC%D1%96%D1%81%D1%82%D1%8C/

@@ -157,9 +157,9 @@ function sendMessage(text) {

</Sandpack>

While this code works, it leaves the door open for "impossible" states. For example, if you forget to call `setIsSent` and `setIsSending` together, you may end up in a situation where both `isSending` and `isSent` are `true` at the same time. The more complex your component is, the harder it is to understand what happened.
Попри те, що цей код працює, він залишає простір для "неможливих" станів. Наприклад, якщо забути викликати `setIsSent` і `setIsSending` разом, то можна опитися в ситуації, коли і `isSending`, і `isSent` мають значення `true` водночас. Чим складніший компонент, тим важче зрозуміти, що трапилося.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Попри те, що цей код працює, він залишає простір для "неможливих" станів. Наприклад, якщо забути викликати `setIsSent` і `setIsSending` разом, то можна опитися в ситуації, коли і `isSending`, і `isSent` мають значення `true` водночас. Чим складніший компонент, тим важче зрозуміти, що трапилося.
Попри те, що цей код працює, він залишає простір для "неможливих" станів. Наприклад, якщо забути викликати `setIsSent` і `setIsSending` разом, то можна опитися в ситуації, коли й `isSending`, й `isSent` мають значення `true` водночас. Чим складніший компонент, тим важче зрозуміти, що трапилося.


**Since `isSending` and `isSent` should never be `true` at the same time, it is better to replace them with one `status` state variable that may take one of *three* valid states:** `'typing'` (initial), `'sending'`, and `'sent'`:
**Оскільки `isSending` та `isSent` ніколи не повинні мати значення `true` водночас, краще замінити їх однією змінною стану `status`, яка може перебувати в одному з *трьох* валідних станів:** `'typing'` (початковий), `'sending'` і `'sent'`:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
**Оскільки `isSending` та `isSent` ніколи не повинні мати значення `true` водночас, краще замінити їх однією змінною стану `status`, яка може перебувати в одному з *трьох* валідних станів:** `'typing'` (початковий), `'sending'` і `'sent'`:
**Оскільки `isSending` та `isSent` ніколи не повинні мати значення `true` одночасно, краще замінити їх однією змінною стану `status`, яка може перебувати в одному з *трьох* валідних станів:** `'typing'` (початковий), `'sending'` і `'sent'`:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants