You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Апісанні тыпаў у `@types/react` уключае таксама і тыпізацыю ўбудаваных хукаў, таму вы можаце выкарыстоўваць іх у сваіх кампанентах без дадатковай налады. Яны пабудаваныя такім чынам, каб улічваць код, ужо напісаны ў кампаненце, такім чынам вы атрымаеце [аўтаматычна вызначаныя тыпы](https://www.typescriptlang.org/docs/handbook/type-inference.html) і ў большасці выпадкаў вам не давядзецца разбірацца з дробнай тыпізацыяй самастойна.
136
128
137
129
Але далей мы разгледзім некалькі прыкладаў, як тыпізаваць хукі.
138
130
139
131
### `useState` {/*typing-usestate*/}
140
132
141
133
[Хук `useState`](/reference/react/useState) будзе выкарыстоўваць значэнне, зададзенае пры ініцыалізацыі, для аўтаматычнага вызначэння тыпу. Напрыклад:
142
-
=======
143
-
The type definitions from `@types/react` include types for the built-in Hooks, so you can use them in your components without any additional setup. They are built to take into account the code you write in your component, so you will get [inferred types](https://www.typescriptlang.org/docs/handbook/type-inference.html) a lot of the time and ideally do not need to handle the minutiae of providing the types.
144
-
145
-
However, we can look at a few examples of how to provide types for Hooks.
146
-
147
-
### `useState` {/*typing-usestate*/}
148
-
149
-
The [`useState` Hook](/reference/react/useState) will re-use the value passed in as the initial state to determine what the type of the value should be. For example:
[Хук `useReducer`](/reference/react/useReducer) — больш скаладаны хук, які прымае функцыю рэд’юсара і першапачатковы стан. Аўтаматычна тып будзе вызначаны па тыпу значэння стану. Таксама вы можаце ўказаць тып стану пры выкліку `useReducer`, але звычайна лепей пакінуць першапачатковы стан:
188
-
=======
189
-
The [`useReducer` Hook](/reference/react/useReducer) is a more complex Hook that takes a reducer function and an initial state. The types for the reducer function are inferred from the initial state. You can optionally provide a type argument to the `useReducer` call to provide a type for the state, but it is often better to set the type on the initial state instead:
190
-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
191
170
192
171
<Sandpack>
193
172
@@ -263,11 +242,7 @@ export default function App() {
263
242
264
243
### `useContext` {/*typing-usecontext*/}
265
244
266
-
<<<<<<< HEAD
267
245
[Хук `useContext`](/reference/react/useContext) — тэхніка для перадачы даных кампанентам уніз па дрэве без неабходнасці перадаваць пропсы цераз кампаненты. Выкарыстоўваецца шляхам стварэння кампанента-правайдара і хука для атрымання даных у даччыных кампанентах.
268
-
=======
269
-
The [`useContext` Hook](/reference/react/useContext) is a technique for passing data down the component tree without having to pass props through components. It is used by creating a provider component and often by creating a Hook to consume the value in a child component.
270
-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
271
246
272
247
Аўтаматычна тып будзе вызначаны згодна з тыпам даных, што былі перададзеныя пры выкліку `createContext`:
273
248
@@ -311,11 +286,7 @@ export default App = AppTSX;
311
286
312
287
Дадзеная тэхніка працуе калі маецца прадвызначанае значэнне, якое мае сэнс, але бываюць сітуацыі, калі такога няма. У такім выпадку разумна будзе скарыстацца `null` у якасці прадвызначанага значэння. Але каб сістэме тыпізацыі было зразумела, трэба відавочна ўказаць тып `ContextShape | null` для `createContext`.
313
288
314
-
<<<<<<< HEAD
315
289
Разам з тым з’яўляецца патрэба выключаць `| null` пры атрыманні значэння. Мы раім дадаць у хук праверку, якая будзе падчас выканання правяраць наяўнасць значэння і выкідваць памылку пры яго адсутнасці:
316
-
=======
317
-
This causes the issue that you need to eliminate the `| null` in the type for context consumers. Our recommendation is to have the Hook do a runtime check for it's existence and throw an error when not present:
// `| null` будзе выключаны пасля таго, як спрацуе хук.
333
-
=======
334
-
// The `| null` will be removed via the check in the Hook.
335
-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
336
303
constuseGetComplexObject= () => {
337
304
constobject=useContext(Context);
338
305
if (!object) { thrownewError("useGetComplexObject must be used within a Provider") }
@@ -362,11 +329,7 @@ function MyComponent() {
362
329
363
330
### `useMemo` {/*typing-usememo*/}
364
331
365
-
<<<<<<< HEAD
366
332
[Хук `useMemo`](/reference/react/useMemo) дапамагае ствараць і паўторна атрымліваць доступ да запомненых вынікаў запуску функцыі. Функцыя будзе выконвацца наноў толькі ў выпадках, калі зменіцца залежнае значэнне, перададзенае другім параметрам. Вынік выкліку функцыі будзе аўтаматычна тыпізаваны адпаведна функцыі, што была перададзеная першым параметрам. Вы можаце тыпізаваць хук відавочна, перадаўшы яму тып.
367
-
=======
368
-
The [`useMemo`](/reference/react/useMemo) Hooks will create/re-access a memorized value from a function call, re-running the function only when dependencies passed as the 2nd parameter are changed. The result of calling the Hook is inferred from the return value from the function in the first parameter. You can be more explicit by providing a type argument to the Hook.
369
-
>>>>>>> fcd00068bd1bdd4eb37e3e0ab0488a9d093670bc
370
333
371
334
```ts
372
335
// Тып visibleTodos вызначаны аўтаматычна з тыпу значэння, што вяртае функцыя filterTodos
[Хук `useCallback`](/reference/react/useCallback) забяспечвае стабільную спасылку на функцыю пакуль залежнасці, перададзеныя другім параметрам, не змяняюцца. Як і `useMemo`, тып функцыі вызначаецца па тыпе функцыі, што перададзеная першым параметрам, але болей відавочна ўказаць тып можна перадаўшы яго ў хук.
381
-
=======
382
-
The [`useCallback`](/reference/react/useCallback) provide a stable reference to a function as long as the dependencies passed into the second parameter are the same. Like `useMemo`, the function's type is inferred from the return value of the function in the first parameter, and you can be more explicit by providing a type argument to the Hook.
0 commit comments