-
Notifications
You must be signed in to change notification settings - Fork 120
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
base: main
Are you sure you want to change the base?
Finish translation of Choosing the State Structure #582
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎ 1 Skipped Deployment
|
Size changes📦 Next.js Bundle Analysis for react-devThis analysis was generated by the Next.js Bundle Analysis action. 🤖 Five Pages Changed SizeThe following pages changed size from the code in this PR compared to its base branch:
DetailsOnly 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 Any third party scripts you have added directly to your app using the 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. |
There was a problem hiding this 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: 'Тайланд', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
title: 'Тайланд', | |
title: 'Таїланд', |
childIds: [] | ||
}, | ||
24: { | ||
id: 24, | ||
title: 'Thailand', | ||
title: 'Тайланд', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
title: 'Тайланд', | |
title: 'Таїланд', |
childIds: [] | ||
}, | ||
24: { | ||
id: 24, | ||
title: 'Thailand', | ||
title: 'Тайланд', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
title: 'Тайланд', | |
title: 'Таїланд', |
childIds: [] | ||
}, | ||
24: { | ||
id: 24, | ||
title: 'Thailand', | ||
title: 'Тайланд', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
title: 'Тайланд', | |
title: 'Таїланд', |
@@ -599,7 +599,7 @@ export default function TravelPlan() { | |||
const planets = plan.childPlaces; | |||
return ( | |||
<> | |||
<h2>Places to visit</h2> | |||
<h2>Місця, варті відвідування</h2> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можливо, краще зробити або без коми, або переробити, або додати які
<h2>Місця, варті відвідування</h2> | |
<h2>Місця для відвідування</h2> |
<h2>Місця, варті відвідування</h2> | |
<h2>Що б відвідати</h2> |
<h2>Місця, варті відвідування</h2> | |
<h2>Що відвідати</h2> |
<h2>Місця, варті відвідування</h2> | |
<h2>Що варто відвідати</h2> |
<h2>Місця, варті відвідування</h2> | |
<h2>Місця, що варті відвідування</h2> |
@@ -2548,7 +2548,7 @@ export default function MailClient() { | |||
<hr /> | |||
<p> | |||
<b> | |||
You selected {selectedCount} letters | |||
Ви обрали {selectedCount} листів |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можливо, краще якийсь варіант, щоби число не узгоджувати?
Ви обрали {selectedCount} листів | |
Ви обрали листи: {selectedCount} |
Чи якось так.
Не хочеться дивитися на "Ви обрали 1 листів" :)
@@ -2624,14 +2624,14 @@ export default function MailClient() { | |||
const selectedCount = selectedIds.length; | |||
|
|||
function handleToggle(toggledId) { | |||
// Was it previously selected? | |||
// Чи був цей лист досі обраним? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
// Чи був цей лист досі обраним? | |
// Чи був цей лист обраним перед цим? |
або якось так, досі тут погано зчитується
if (selectedIds.includes(toggledId)) { | ||
// Then remove this ID from the array. | ||
// Тоді вилучіть цей ідентифікатор з масиву. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
// Тоді вилучіть цей ідентифікатор з масиву. | |
// Тоді вилучіть цей ідентифікатор із масиву. |
setSelectedIds(selectedIds.filter(id => | ||
id !== toggledId | ||
)); | ||
} else { | ||
// Otherwise, add this ID to the array. | ||
// Інакше – додайте цей ідентифікатор до масиву. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
// Інакше – додайте цей ідентифікатор до масиву. | |
// Інакше додайте цей ідентифікатор до масиву. |
@@ -2734,7 +2734,7 @@ export default function MailClient() { | |||
const selectedCount = selectedIds.size; | |||
|
|||
function handleToggle(toggledId) { | |||
// Create a copy (to avoid mutation). | |||
// Створити копію (для запобігання внесенню змін). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
// Створити копію (для запобігання внесенню змін). | |
// Створити копію (для запобігання мутаціям). |
|
||
This menu list component lets you choose a single travel snack out of several: | ||
Цей компонент списку меню дає змогу обрати один дорожній перекус з кількох: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Усі обрати/обрали замінити на вибрати/...
Обирають на посаду
There was a problem hiding this 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. | ||
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати та зневаджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати при структуруванні стану. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати та зневаджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати при структуруванні стану. | |
Структура стану може утворювати разючу різницю між компонентом, який приємно змінювати або налагоджувати, та компонентом, який є постійним джерелом дефектів. Ось кілька порад, які варто обдумати під час структурування стану. |
* What to avoid when organizing state | ||
* How to fix common issues with the state structure | ||
* Коли використовувати одну змінну стану, а коли – декілька | ||
* Чого слід уникати при організації стану |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
* Чого слід уникати при організації стану | |
* Чого слід уникати під час організації стану |
* When to use a single vs multiple state variables | ||
* What to avoid when organizing state | ||
* How to fix common issues with the state structure | ||
* Коли використовувати одну змінну стану, а коли – декілька |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
* Коли використовувати одну змінну стану, а коли – декілька | |
* Коли використовувати одну змінну стану, а коли — декілька |
|
||
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), щоб знизити шанс появи дефектів. Перефразовуючи Альберта Ейнштейна, **"Роби свій стан простим, як можливо, – але не простіше цього."** |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мета цих принципів – *щоб стан було легко оновлювати без додавання помилок*. Вилучення зі стану надлишкових і продубльованих даних допомагає пересвідчитися, що всі частини синхронізовані одна з одною. Це схоже на те, як інженер баз даних міг би ["нормалізуватИ" структуру бази даних](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. | |||
Ще одна ситуація, коли дані групують в об'єкт чи масив, – це коли невідомо, скільки порцій стану знадобиться. Наприклад, це допомагає, коли є форма, куди користувач може додати власні поля. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ще одна ситуація, коли дані групують в об'єкт чи масив, – це коли невідомо, скільки порцій стану знадобиться. Наприклад, це допомагає, коли є форма, куди користувач може додати власні поля. | |
Ще одна ситуація, коли дані групують в об'єкт чи масив, — це коли невідомо, яка частина стану знадобиться. Наприклад, це допомагає, коли є форма, в якій користувач може додавати власні поля. |
@@ -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`. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Проблема в тому, що об'єкт листа зберігається в `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: | ||
Технічно можна зробити і так, і так. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете завжди підтримувати їхню синхронізацію, як у цьому прикладі, де рухання курсора оновлює обидві координати червоної крапки: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Технічно можна зробити і так, і так. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете завжди підтримувати їхню синхронізацію, як у цьому прикладі, де рухання курсора оновлює обидві координати червоної крапки: | |
Технічно можна зробити і перше, і друге. Але **якщо якісь дві змінні стану завжди змнюються разом, можливо, краще об'єднати їх в одну змінну стану.** Тоді ви не забудете повсякчас підтримувати їхню синхронізацію, як у цьому прикладі, де рух курсора оновлює обидві координати червоної крапки: |
тавтології
|
||
<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)`. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Якщо ваша змінна стану є об'єктом, пам'ятайте, що [не можна оновлювати лише одне поле в цьому об'єкті](/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` водночас. Чим складніший компонент, тим важче зрозуміти, що трапилося. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Попри те, що цей код працює, він залишає простір для "неможливих" станів. Наприклад, якщо забути викликати `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'`: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
**Оскільки `isSending` та `isSent` ніколи не повинні мати значення `true` водночас, краще замінити їх однією змінною стану `status`, яка може перебувати в одному з *трьох* валідних станів:** `'typing'` (початковий), `'sending'` і `'sent'`: | |
**Оскільки `isSending` та `isSent` ніколи не повинні мати значення `true` одночасно, краще замінити їх однією змінною стану `status`, яка може перебувати в одному з *трьох* валідних станів:** `'typing'` (початковий), `'sending'` і `'sent'`: |
No description provided.