-
Notifications
You must be signed in to change notification settings - Fork 125
Translation FAQ: Component State #66
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7face43
translation faq-component-state
marichka-offen 9d00f31
Update faq-state.md
marichka-offen 4c9dbed
Apply suggestions from code review
oleksii-polovyi db61025
Update faq-state.md
marichka-offen 3371971
Update content/docs/faq-state.md
vldmrkl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,106 +1,106 @@ | ||
--- | ||
id: faq-state | ||
title: Component State | ||
title: Стан компонента | ||
permalink: docs/faq-state.html | ||
layout: docs | ||
category: FAQ | ||
--- | ||
|
||
### What does `setState` do? {#what-does-setstate-do} | ||
### Для чого потрібен метод `setState`? {#what-does-setstate-do} | ||
|
||
`setState()` schedules an update to a component's `state` object. When state changes, the component responds by re-rendering. | ||
Метод `setState()` призначає зміни об'єкта `стану (state)`. У відповідь на зміни стану компонент рендериться повторно. | ||
|
||
### What is the difference between `state` and `props`? {#what-is-the-difference-between-state-and-props} | ||
### У чому полягає різниця між `state` та `props`? {#what-is-the-difference-between-state-and-props} | ||
|
||
[`props`](/docs/components-and-props.html) (short for "properties") and [`state`](/docs/state-and-lifecycle.html) are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: `props` get passed *to* the component (similar to function parameters) whereas `state` is managed *within* the component (similar to variables declared within a function). | ||
[`props`](/docs/components-and-props.html) (скороч. від англ. "properties" — властивості) і [`state`](/docs/state-and-lifecycle.html) — це звичайні JavaScript-об'єкти. Хоча обидва містять інформацію, що впливає на результат рендерингу, існує одна істотна відмінність: `props` *передаються в* компонент (подібно до параметрів функції), у той час як `state` *знаходиться у* компоненті (подібно до оголошення змінних усередині функції). | ||
|
||
Here are some good resources for further reading on when to use `props` vs `state`: | ||
Для подальшого ознайомлення з поняттями `пропсів` та `стану` рекомендуємо наступні статті: | ||
* [Props vs State](https://github.com/uberVU/react-guide/blob/master/props-vs-state.md) | ||
* [ReactJS: Props vs. State](https://lucybain.com/blog/2016/react-state-vs-pros/) | ||
|
||
### Why is `setState` giving me the wrong value? {#why-is-setstate-giving-me-the-wrong-value} | ||
### Чому `setState` видає невірне значення? {#why-is-setstate-giving-me-the-wrong-value} | ||
|
||
In React, both `this.props` and `this.state` represent the *rendered* values, i.e. what's currently on the screen. | ||
У React, як `this.props`, так і `this.state` представляють уже *відрендерені* значення, тобто те що наразі знаходиться на екрані. | ||
|
||
Calls to `setState` are asynchronous - don't rely on `this.state` to reflect the new value immediately after calling `setState`. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details). | ||
Виклик `setState` — асинхронний, тому не варто розраховувати, що `this.state` відобразить нове значення відразу ж після виклику. Якщо вам потрібно розрахувати значення, засновані на поточному стані, замість об'єкта передайте функцію оновлення (детальну інформацію див. нижче). | ||
|
||
Example of code that will *not* behave as expected: | ||
Приклад коду, що *не* працюватиме належним чином: | ||
|
||
```jsx | ||
incrementCount() { | ||
// Note: this will *not* work as intended. | ||
// Примітка: код *не* працюватиме належним чином. | ||
this.setState({count: this.state.count + 1}); | ||
} | ||
|
||
handleSomething() { | ||
// Let's say `this.state.count` starts at 0. | ||
// Припустимо, що `this.state.count` починається з 0. | ||
this.incrementCount(); | ||
this.incrementCount(); | ||
this.incrementCount(); | ||
// When React re-renders the component, `this.state.count` will be 1, but you expected 3. | ||
// Коли React повторно відрендерить компонент, `this.state.count` буде дорівнювати 1 замість очікуваних 3. | ||
|
||
// This is because `incrementCount()` function above reads from `this.state.count`, | ||
// but React doesn't update `this.state.count` until the component is re-rendered. | ||
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1. | ||
// Це відбувається тому, що попередня функція — `incrementCount()` бере своє значення зі `this.state.count`, | ||
// але React не оновить `this.state.count` доки компонент не відрендериться повторно. | ||
// Тож, кожного разу `incrementCount()` зчитує значення this.state.count як 0 і встановлює його рівним 1. | ||
|
||
// The fix is described below! | ||
// Нижче розглянемо як вирішити дану проблему! | ||
} | ||
``` | ||
|
||
See below for how to fix this problem. | ||
Див. нижче як вирішити цю проблему! | ||
|
||
### How do I update state with values that depend on the current state? {#how-do-i-update-state-with-values-that-depend-on-the-current-state} | ||
### Як оновити значення, що залежить від поточного стану? {#how-do-i-update-state-with-values-that-depend-on-the-current-state} | ||
|
||
Pass a function instead of an object to `setState` to ensure the call always uses the most updated version of state (see below). | ||
Замість об'єкта передайте до `setState` функцію, щоб впевнитись, що виклик завжди використовує актуальну версію стану (див. нижче). | ||
|
||
### What is the difference between passing an object or a function in `setState`? {#what-is-the-difference-between-passing-an-object-or-a-function-in-setstate} | ||
### У чому полягає різниця між передачею об'єкта або функції у `setState`? {#what-is-the-difference-between-passing-an-object-or-a-function-in-setstate} | ||
|
||
Passing an update function allows you to access the current state value inside the updater. Since `setState` calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting: | ||
Передача функції оновлення надає доступ до поточного стану всередині самої функції. Оскільки виклики `setState` згруповані, це дозволяє послідовно виконати оновлення і гарантує те, що зміни будуть виконуватися по черзі, а не конфліктувати одна з одною: | ||
|
||
```jsx | ||
incrementCount() { | ||
this.setState((state) => { | ||
// Important: read `state` instead of `this.state` when updating. | ||
// Важливо: використовуйте `state` замість `this.state` при оновленні. | ||
return {count: state.count + 1} | ||
}); | ||
} | ||
|
||
handleSomething() { | ||
// Let's say `this.state.count` starts at 0. | ||
// Припустимо, що `this.state.count` починається з 0. | ||
this.incrementCount(); | ||
this.incrementCount(); | ||
this.incrementCount(); | ||
|
||
// If you read `this.state.count` now, it would still be 0. | ||
// But when React re-renders the component, it will be 3. | ||
// Значення `this.state.count` все ще дорівнює 0. | ||
// Але коли React повторно відрендерить компонент, значення дорівнюватиме 3. | ||
} | ||
``` | ||
|
||
[Learn more about setState](/docs/react-component.html#setstate) | ||
[Дізнатись більше про setState](/docs/react-component.html#setstate) | ||
|
||
### When is `setState` asynchronous? {#when-is-setstate-asynchronous} | ||
### Коли `setState` працює асинхронно? {#when-is-setstate-asynchronous} | ||
|
||
Currently, `setState` is asynchronous inside event handlers. | ||
Наразі, `setState` працює асинхронно усередині обробників подій. | ||
|
||
This ensures, for example, that if both `Parent` and `Child` call `setState` during a click event, `Child` isn't re-rendered twice. Instead, React "flushes" the state updates at the end of the browser event. This results in significant performance improvements in larger apps. | ||
Це гарантує, наприклад, що якщо `Батьківський` та `Дочірній` компоненти викликають `setState` під час натискання, то `Дочірній` компонент не буде відрендерений двічі. Замість цього, React "відкладає" оновлення стану до моменту закінчення роботи події. Це допомагає значно підвищити продуктивність великих додатків. | ||
|
||
This is an implementation detail so avoid relying on it directly. In the future versions, React will batch updates by default in more cases. | ||
Це деталь реалізації, а тому не покладайтесь на неї безпосередньо. У майбутніх версіях React буде за замовчуванням групувати оновлення стану. | ||
|
||
### Why doesn't React update `this.state` synchronously? {#why-doesnt-react-update-thisstate-synchronously} | ||
### Чому React не оновлює `this.state` синхронно? {#why-doesnt-react-update-thisstate-synchronously} | ||
|
||
As explained in the previous section, React intentionally "waits" until all components call `setState()` in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders. | ||
Як згадувалось раніше, перед початком повторного рендерингу React навмисно "очікує" доки всі компоненти викличуть `setState()` у своїх обробниках подій. Це дозволяє прискорити продуктивність уникаючи повторного рендерингу. | ||
|
||
However, you might still be wondering why React doesn't just update `this.state` immediately without re-rendering. | ||
У вас може виникнути питання, чому React просто відразу не оновить `this.state`. | ||
|
||
There are two main reasons: | ||
Існує дві причини: | ||
|
||
* This would break the consistency between `props` and `state`, causing issues that are very hard to debug. | ||
* This would make some of the new features we're working on impossible to implement. | ||
* Це порушить узгодженість між `props` та `state`, спричиняючи велику кількість помилок. | ||
* Це зробить реалізацію нових функцій неможливою. | ||
|
||
This [GitHub comment](https://github.com/facebook/react/issues/11527#issuecomment-360199710) dives deep into the specific examples. | ||
У цьому [GitHub-коментарі](https://github.com/facebook/react/issues/11527#issuecomment-360199710) дана тема розглядається глибше. | ||
|
||
### Should I use a state management library like Redux or MobX? {#should-i-use-a-state-management-library-like-redux-or-mobx} | ||
### Чи варто використовувати бібліотеки управління станом, такі як Redux чи MobX? {#should-i-use-a-state-management-library-like-redux-or-mobx} | ||
|
||
[Maybe.](https://redux.js.org/faq/general#when-should-i-use-redux) | ||
[Можливо.](https://redux.js.org/faq/general#when-should-i-use-redux) | ||
|
||
It's a good idea to get to know React first, before adding in additional libraries. You can build quite complex applications using only React. | ||
Перед застосуванням додаткових бібліотек варто досконало вивчити React. Використовуючи тільки його можна створити досить складні додатки. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.