From 279444fc4764dc75eda2b744ac9e0e7268fdc195 Mon Sep 17 00:00:00 2001 From: Arkadiusz Mazurkiewicz Date: Sat, 13 Apr 2019 13:45:46 +0200 Subject: [PATCH 1/8] Translate `React.Component` section. --- content/docs/reference-react-component.md | 356 +++++++++--------- .../get-snapshot-before-update.js | 12 +- 2 files changed, 184 insertions(+), 184 deletions(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index ecb4d087c..9b40c983c 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -15,50 +15,50 @@ redirect_from: - "tips/use-react-with-other-libraries.html" --- -This page contains a detailed API reference for the React component class definition. It assumes you're familiar with fundamental React concepts, such as [Components and Props](/docs/components-and-props.html), as well as [State and Lifecycle](/docs/state-and-lifecycle.html). If you're not, read them first. +Ta strona zawiera szegółowe odniesienie do definicji klasy reactowego komponentu. Zakłada ona, że znasz fundamentalne zagadnienia Reacta, takie jak [Komponenty i właściwości](/docs/components-and-props.html), i [Stan i cykl życia](/docs/state-and-lifecycle.html). Jeśli nie, zapoznaj się najpierw z nimi. -## Overview {#overview} +## Ogólne informacje {#overview} -React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend `React.Component`: +React pozwala na zdefiniowanie komponentów jako klasy lub funkcje. Komponenty zdefiniowane jako klasy obecnie zapewniają więcej funkcjonalności, które szczegółowo opiszemy na tej stronie. Aby komponent mógł być zdefiniowany jako klasa, musi on dziedziczyć po klasie `React.Component`: ```js class Welcome extends React.Component { render() { - return

Hello, {this.props.name}

; + return

Cześć, {this.props.name}

; } } ``` -The only method you *must* define in a `React.Component` subclass is called [`render()`](#render). All the other methods described on this page are optional. +Jedyna metoda, która *musi* być zdefiniowana w klasie dziedziczącej po `React.Component` nazywa się [`render()`](#render). Wszystkie inne metody opisane na tej stronie są opcjonalne. -**We strongly recommend against creating your own base component classes.** In React components, [code reuse is primarily achieved through composition rather than inheritance](/docs/composition-vs-inheritance.html). +**Stanowczo odradadzamy tworzenie własnych klas bazowych komponentów.** W Reactowych komponentach [wielokrotne użycie kodu jest osiągane przede wszystkim przez kompozycję, a nie dziedziczenie](/docs/composition-vs-inheritance.html). ->Note: +>Uwaga: > ->React doesn't force you to use the ES6 class syntax. If you prefer to avoid it, you may use the `create-react-class` module or a similar custom abstraction instead. Take a look at [Using React without ES6](/docs/react-without-es6.html) to learn more. +>React nie zmusza cię do stosowania składni klasy ze standardu ES6. Jeśli wolisz jej uniknąć, możesz zamiast niej użyć modułu `create-react-class` lub podobnej niestandardowej abstrakcji. Aby dowiedzieć się więcej, zobacz rozdział [React bez ES6](/docs/react-without-es6.html). -### The Component Lifecycle {#the-component-lifecycle} +### Cykl życia komponentu {#the-component-lifecycle} -Each component has several "lifecycle methods" that you can override to run code at particular times in the process. **You can use [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) as a cheat sheet.** In the list below, commonly used lifecycle methods are marked as **bold**. The rest of them exist for relatively rare use cases. +Każdy komponent ma kilka "metod cyklu życia", które możesz nadpisać, aby uruchomić kod w szczególnych momentach programu. **Możesz użyć [tego diagramu cyklu życia](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) jako ściągawki.** Na liście poniżej, często używane metody cyklu życia zostały **pogrubione**. Reszta z nich istnieje dla stosunkowo rzadkich przypadków użycia. -#### Mounting {#mounting} +#### Montowanie {#mounting} -These methods are called in the following order when an instance of a component is being created and inserted into the DOM: +Podczas, gdy instancja komponentu zostaje stworzona i włożona do drzewa DOM, w podanej kolejności wywołwane są poniższe metody: - [**`constructor()`**](#constructor) - [`static getDerivedStateFromProps()`](#static-getderivedstatefromprops) - [**`render()`**](#render) - [**`componentDidMount()`**](#componentdidmount) ->Note: +>Uwaga: > ->These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code: +>Te metody są uznawane za przestarzałe (ang. *legacy*) i powinno się [ich unikać](/blog/2018/03/27/update-on-async-rendering.html) w nowym kodzie: > >- [`UNSAFE_componentWillMount()`](#unsafe_componentwillmount) -#### Updating {#updating} +#### Aktualizacja {#updating} -An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered: +Aktualizacja może być spowodowana zmianami we właściwościach lub stanie komponentu. Kiedy komponent zostaje ponownie zrenderowany, w podanej kolejności wywołane zostają poniższe metody: - [`static getDerivedStateFromProps()`](#static-getderivedstatefromprops) - [`shouldComponentUpdate()`](#shouldcomponentupdate) @@ -66,50 +66,50 @@ An update can be caused by changes to props or state. These methods are called i - [`getSnapshotBeforeUpdate()`](#getsnapshotbeforeupdate) - [**`componentDidUpdate()`**](#componentdidupdate) ->Note: +>Uwaga: > ->These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code: +>Te metody są uznawane za przestarzałe i powinno się [ich unikać](/blog/2018/03/27/update-on-async-rendering.html) w nowym kodzie: > >- [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate) >- [`UNSAFE_componentWillReceiveProps()`](#unsafe_componentwillreceiveprops) -#### Unmounting {#unmounting} +#### Odmontowywanie {#unmounting} -This method is called when a component is being removed from the DOM: +Kiedy komponent zostaje usunięty z drzewa DOM, wywołana zostaje poniższa metoda: - [**`componentWillUnmount()`**](#componentwillunmount) -#### Error Handling {#error-handling} +#### Obsługa wyjątków {#error-handling} -These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component. +Poniższe metody zostają wywołane w razie wystąpienia wyjątku podczas renderowania, w metodzie cyklu życia, lub w konstruktorze dowolnych komponentów potomnych. - [`static getDerivedStateFromError()`](#static-getderivedstatefromerror) - [`componentDidCatch()`](#componentdidcatch) -### Other APIs {#other-apis} +### Inne API {#other-apis} -Each component also provides some other APIs: +Każdy komponent zapewnia też kilka innych API: - [`setState()`](#setstate) - [`forceUpdate()`](#forceupdate) -### Class Properties {#class-properties} +### Właściwości klasy {#class-properties} - [`defaultProps`](#defaultprops) - [`displayName`](#displayname) -### Instance Properties {#instance-properties} +### Właściwości instancji {#instance-properties} - [`props`](#props) - [`state`](#state) * * * -## Reference {#reference} +## Dokumentacja {#reference} -### Commonly Used Lifecycle Methods {#commonly-used-lifecycle-methods} +### Powszechnie używane metody cyklu życia {#commonly-used-lifecycle-methods} -The methods in this section cover the vast majority of use cases you'll encounter creating React components. **For a visual reference, check out [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).** +Metody opisane w tym rozdziale pokrywają zdecydowaną większość przypadków użycia, na które natkniesz się tworząc reactowe komponenty. **Dla odniesienia wizualnego, zobacz [ten diagram cyklu życia](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).** ### `render()` {#render} @@ -117,23 +117,23 @@ The methods in this section cover the vast majority of use cases you'll encounte render() ``` -The `render()` method is the only required method in a class component. +Metoda `render()` jest jedyną metodą wymaganą w komponencie klasowym. -When called, it should examine `this.props` and `this.state` and return one of the following types: +Wywołana, powinna sprawdzić `this.props` i `this.state` oraz zwrócić jeden z poniższych typów: -- **React elements.** Typically created via [JSX](/docs/introducing-jsx.html). For example, `
` and `` are React elements that instruct React to render a DOM node, or another user-defined component, respectively. -- **Arrays and fragments.** Let you return multiple elements from render. See the documentation on [fragments](/docs/fragments.html) for more details. -- **Portals**. Let you render children into a different DOM subtree. See the documentation on [portals](/docs/portals.html) for more details. -- **String and numbers.** These are rendered as text nodes in the DOM. -- **Booleans or `null`**. Render nothing. (Mostly exists to support `return test && ` pattern, where `test` is boolean.) +- **Reactowe elementy.** Zwykle tworzone poprzez [JSX](/docs/introducing-jsx.html). Na przykład, `
` i `` są reactowymi elementami, które instruują Reacta, aby, odpowiednio, zrenderował węzeł drzewa DOM, lub inny zdefiniowany przez użytkownika komponent. +- **Tablice i fragmenty.** Pozwalają na zwrócenie wielu elementów z metody render. Po więcej szczegółów odwiedź dokumentację [fragmentów](/docs/fragments.html). +- **Portale**. Pozwalają na zrenderowanie elementów potomnych w innym poddrzewie DOM. Po więcej szczegółów odwiedź dokumentację [portali](/docs/portals.html). +- **Łańcuchy znaków i liczby.** Zostają zrenderowane jako węzły tekstowe w drzewie DOM. +- **Typ logiczny lub `null`**. Nie renderuje nic. (Istnieje głównie, aby wspierać wzorzec `return test && `, gdzie `test` jest wartością logiczną.) -The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. +Funkcja `render()` powinna być czysta, to znaczy, że nie modyfikuje stanu komponentu, zwraca ten sam wynik przy każdym wywołaniu, i nie wchodzi w bezpośrednią interakcję z przeglądarką. -If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about. +Jeśli potrzebujesz wejść w interakcję z przeglądarką, zamiast tego wykonaj swoje instrukcje w `componentDidMount()` lub innych metodach cyklu życia. Utrzymywanie funkcji `render()` w czystości sprawia, że łatwiej jest myśleć o komponentach. -> Note +> Uwaga > -> `render()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false. +> Funkcja `render()` nie zostanie wywołana, jeśli [`shouldComponentUpdate()`](#shouldcomponentupdate) zwróci `false`. * * * @@ -143,47 +143,47 @@ If you need to interact with the browser, perform your work in `componentDidMoun constructor(props) ``` -**If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.** +**Jeśli nie inicjalizujesz stanu i nie wiążesz (ang. *bind*) metod, nie ma potrzeby, abyś implementował konstruktor w swoim reactowym komponencie.** -The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs. +Konstruktor reactowego komponentu jest wywoływany przed jego zamontowaniem. Kiedy implementujesz konstruktor w klasie dziedziczącej po klasie `React.Component`, powinieneś wywołać metodę `super(props)` przed jakąkolwiek inną instrukcją. W innym wypadku, `this.props` będzie miało w konstruktorze wartość `undefined`, co może prowadzić do błędów. -Typically, in React constructors are only used for two purposes: +Zazwyczaj, konstruktory są używane tylko w dwóch celach: -* Initializing [local state](/docs/state-and-lifecycle.html) by assigning an object to `this.state`. -* Binding [event handler](/docs/handling-events.html) methods to an instance. +* Inicjalizacji [stanu lokalnego](/docs/state-and-lifecycle.html) przez przypisanie obiektu do `this.state`. +* Związania [metody obsługującej zdarzenia](/docs/handling-events.html) z instancją komponentu. -You **should not call `setState()`** in the `constructor()`. Instead, if your component needs to use local state, **assign the initial state to `this.state`** directly in the constructor: +**Nie powinieneś wywoływać metody `setState()`** w funkcji `constructor()`. Zamiast tego, jeśli potrzebujesz użyć w komponencie stanu lokalnego, **przydziel początkowy stan do `this.state`** bezpośrednio w konstruktorze: ```js constructor(props) { super(props); - // Don't call this.setState() here! + // Nie wywołuj tutaj this.setState()! this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); } ``` -Constructor is the only place where you should assign `this.state` directly. In all other methods, you need to use `this.setState()` instead. +Konstruktor jest jedynym miejscem, w którym powinieneś przypisywać `this.state` bezpośrednio. Natomiast we wszystkich innych metodach powinieneś używać `this.setState()`. -Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use `componentDidMount()` instead. +Unikaj wprowadzania efektów ubocznych lub subskrypcji w konstruktorze. Używaj zamiast tego `componentDidMount()` dla tych przypadków użycia. ->Note +>Uwaga > ->**Avoid copying props into state! This is a common mistake:** +>**Unikaj kopiowania właściwości do stanu! Jest to częsty błąd:** > >```js >constructor(props) { > super(props); -> // Don't do this! +> // Nie rób tego! > this.state = { color: props.color }; >} >``` > ->The problem is that it's both unnecessary (you can use `this.props.color` directly instead), and creates bugs (updates to the `color` prop won't be reflected in the state). +>Problem w tym, że jest to jednocześnie niepotrzebne (zamiast tego możesz użyć `this.props.color` bezpośrednio), i jest przyczyną błędów (aktualizacje właściwości `color` nie będą odzwierciedlane w stanie). > ->**Only use this pattern if you intentionally want to ignore prop updates.** In that case, it makes sense to rename the prop to be called `initialColor` or `defaultColor`. You can then force a component to "reset" its internal state by [changing its `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) when necessary. +>**Używaj tego wzorca tylko jeśli chcesz celowo ignorować aktualizacje właściwości.** W tym wypadku, bedzie miała sens zmiana nazwy właściwości na `initialColor` (ang. *początkowy kolor*) lub `defaultColor` (ang. *domyślny kolor*). Możesz wtedy zmusić komponent do "zresetowania" swojego wewnętrznego stanu przez [zmianę jego właściwości `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) w razie potrzeby. > ->Read our [blog post on avoiding derived state](/blog/2018/06/07/you-probably-dont-need-derived-state.html) to learn about what to do if you think you need some state to depend on the props. +>Przeczytaj nasz [wpis na blogu na temat unikania stanu pochodnego](/blog/2018/06/07/you-probably-dont-need-derived-state.html), aby dowiedzieć się co należy zrobić, jeśli wydaje ci się, że potrzebujesz stanu zależnego od właściwości. * * * @@ -194,11 +194,11 @@ Avoid introducing any side-effects or subscriptions in the constructor. For thos componentDidMount() ``` -`componentDidMount()` is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. +Metoda `componentDidMount()` jest wywołowana bezpośrednio po zamontowaniu komponentu (po jego włożeniu do drzewa). Inicjalizacja, która wymaga węzłów drzewa DOM powinna się tam znaleźć. Jeśli potrzebujesz załadować dane ze zdalnego zasobu, jest to dobre miejsce do wykonania zapytania sieciowego. -This method is a good place to set up any subscriptions. If you do that, don't forget to unsubscribe in `componentWillUnmount()`. +Ta metoda jest dobrym miejscem na przygotowanie dowolnych subskrypcji. Jeśli to zrobisz, nie zapomnij ich zakończyć w metodzie `componentWillUnmount()`. -You **may call `setState()` immediately** in `componentDidMount()`. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the `render()` will be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the `constructor()` instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position. +**Możesz wywołać metodę `setState()` od razu** w `componentDidMount()`. Spowoduje to dodatkowe renderowanie, ale zostanie ono wykonane zanim przeglądarka zaktualizuje ekran. Jest to gwarancją, że pomimo, iż metoda `render()` będzie w tym przypadku wywołana dwa razy, użytkownik nie zobaczy pośredniego stanu. Używaj tego wzorca uważnie, ponieważ często powoduje on problemy z wydajnością. W większości przypadków, powinieneś zamiast tego mieć możliwość przypisania stanu początkowego w konstruktorze. Może to być natomiast konieczne w przypadkach takich jak okna modalne i okienka podpowiedzi, kiedy przed zrenderowaniem czegoś trzeba zmierzyć węzeł drzewa DOM. * * * @@ -208,26 +208,26 @@ You **may call `setState()` immediately** in `componentDidMount()`. It will trig componentDidUpdate(prevProps, prevState, snapshot) ``` -`componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render. +Metoda `componentDidUpdate()` jest wywoływana bezpośrednio po wystąpieniu aktualizacji. Nie jest ona wywoływana po początkowym zrenderowaniu. -Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). +Używaj tego jako okazji do operacji na drzewie DOM kiedy komponent został zaktualizowany. Jest to także dobre miejsce na wykonywanie zapytań sieciowych tak długo jak porównujesz obecne właściwości z poprzednimi (na przykład, zapytanie może być niepotrzebne jeśli właściwości się nie zmieniły). ```js componentDidUpdate(prevProps) { - // Typical usage (don't forget to compare props): + // Typowy sposób użycia (nie zapomnij porównać właściwości): if (this.props.userID !== prevProps.userID) { this.fetchData(this.props.userID); } } ``` -You **may call `setState()` immediately** in `componentDidUpdate()` but note that **it must be wrapped in a condition** like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you're trying to "mirror" some state to a prop coming from above, consider using the prop directly instead. Read more about [why copying props into state causes bugs](/blog/2018/06/07/you-probably-dont-need-derived-state.html). +**Możesz wywołać metodę `setState()` od razu** w `componentDidUpdate()`, ale weź pod uwagę, że **musi ona być owinięta instrukcją warunkową** jak w przykładzie powyżej, albo spowodujesz nieskończoną pętlę. Spowodowałoby to również dodatkowe renderowanie które, pomimo że niedostrzegalne dla użytkownika, może negatywnie wpłynąć na wydajność komponentu. Jeśli próbujesz "odzwierciedlić" pewien stan z właściwością pochodzącą z góry, rozważ zamiast tego użycie tej właściwości bezpośrednio. Dowiedz się więcej o tym [dlaczego kopiowanie właściwości do stanu powoduje błędy](/blog/2018/06/07/you-probably-dont-need-derived-state.html). -If your component implements the `getSnapshotBeforeUpdate()` lifecycle (which is rare), the value it returns will be passed as a third "snapshot" parameter to `componentDidUpdate()`. Otherwise this parameter will be undefined. +Jeśli twój komponent ma zaimplementowaną metodę cyklu życia `getSnapshotBeforeUpdate()` (co jest rzadkie), wartość którą ona zwróci, będzie przekazana jako trzeci parametr ("zrzut" (ang.*snapshot*)) do metody `componentDidUpdate()`. W innym wypadku ten parametr będzie miał wartość `undefined`. -> Note +> Uwaga > -> `componentDidUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false. +> Metoda `componentDidUpdate()` nie będzie wywołana jeśli [`shouldComponentUpdate()`](#shouldcomponentupdate) zwróci `false`. * * * @@ -237,15 +237,15 @@ If your component implements the `getSnapshotBeforeUpdate()` lifecycle (which is componentWillUnmount() ``` -`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in `componentDidMount()`. +Metoda `componentWillUnmount()` jest wywoływana zaraz przed odmontowaniem i zniszczeniem komponentu. Przeprowadź potrzebne czyszczenie w tej metodzie, takie jak unieważnienie liczników czasu, anulowanie zapytań sieciowych, lub czyszczenie subskrypcji, które były rozpoczęte w `componentDidMount()`. -You **should not call `setState()`** in `componentWillUnmount()` because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again. +**Nie powinieneś wywoływać metody `setState()`** w `componentWillUnmount()`, ponieważ ten komponent nie zostanie ponownie zrenderowany. Kiedy instancja komponentu zostaje odmonotowana, nigdy nie będzie zamontowana ponownie. * * * -### Rarely Used Lifecycle Methods {#rarely-used-lifecycle-methods} +### Rzadko używane metody cyklu życia {#rarely-used-lifecycle-methods} -The methods in this section correspond to uncommon use cases. They're handy once in a while, but most of your components probably don't need any of them. **You can see most of the methods below on [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) if you click the "Show less common lifecycles" checkbox at the top of it.** +Metody zawarte w tej sekcji odpowiadają rzadkim przypadkom użycia. Czasem są przydatnę, ale większość twoich komponentów najprawdopodobniej nie będzie ich potrzebowała. **Większość poniższych metod możesz zobaczyć na [tym diagramie cyklu życia](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) po kliknięciu na checkbox "Pokaż rzadziej używane metody" u góry.** ### `shouldComponentUpdate()` {#shouldcomponentupdate} @@ -254,17 +254,17 @@ The methods in this section correspond to uncommon use cases. They're handy once shouldComponentUpdate(nextProps, nextState) ``` -Use `shouldComponentUpdate()` to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. +Używaj metody `shouldComponentUpdate()`, aby dać znać Reactowi, czy obecna zmiana stanu lub właściwości komponentu nie wpłynęła na jego wynik. Domyślnym zachowaniem, na którym powinieneś polegać w większości przypadków, jest ponowne renderowanie przy każdej zmianie stanu. -`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when `forceUpdate()` is used. +Metoda `shouldComponentUpdate()` jest wywoływana przed renderowaniem, gdy otrzymywane są nowe właściwości lub stan. Domylnie wartość zwracana to `true`. Ta metoda nie jest wywoływana przy początkowym renderowaniu lub kiedy została użyta metoda `forceUpdate()`. -This method only exists as a **[performance optimization](/docs/optimizing-performance.html).** Do not rely on it to "prevent" a rendering, as this can lead to bugs. **Consider using the built-in [`PureComponent`](/docs/react-api.html#reactpurecomponent)** instead of writing `shouldComponentUpdate()` by hand. `PureComponent` performs a shallow comparison of props and state, and reduces the chance that you'll skip a necessary update. +Ta metoda istnieje tylko jako **[optymalizacja wydajności](/docs/optimizing-performance.html).** Nie polegaj na niej aby "zapobiegać" renderowaniu, co może prowadzić do błędów. Zamiast pisania `shouldComponentUpdate()` własnoręcznie, **rozważ użycie wbudowanej klasy [`PureComponent`](/docs/react-api.html#reactpurecomponent)**. `PureComponent` przeprowadza płytkie porównanie właściwości i stanu, i obniża szansę na pominięcie niezbędnej aktualizacji. -If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped. Note that returning `false` does not prevent child components from re-rendering when *their* state changes. +Jeśli jesteś pewny, że chcesz ją napisać własnoręcznie, możesz porównać `this.props` z `nextProps` i `this.state` z `nextState` oraz zwrócić `false`, aby powiadomić Reacta, że aktualizacja może zostać pominięta. Zauważ, że zwrócenie `false` nie zapobiega ponownemu zrenderowaniu komponentów potomnych, gdy *ich* stan się zmienia. -We do not recommend doing deep equality checks or using `JSON.stringify()` in `shouldComponentUpdate()`. It is very inefficient and will harm performance. +Nie zalecamy wykonywania głębokich porównań lub używania `JSON.stringify()` w metodzie `shouldComponentUpdate()`. Jest to bardzo nieefektywne i negatywnie odbije się na wydajności. -Currently, if `shouldComponentUpdate()` returns `false`, then [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render), and [`componentDidUpdate()`](#componentdidupdate) will not be invoked. In the future React may treat `shouldComponentUpdate()` as a hint rather than a strict directive, and returning `false` may still result in a re-rendering of the component. +Obecnie, jeśli `shouldComponentUpdate()` zwróci `false`, [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render) i [`componentDidUpdate()`](#componentdidupdate) nie zostana wywołane. W przyszłosci React może traktować `shouldComponentUpdate()` jako wskazówkę, a nie jako ścisłą dyrektywę, a zwrócenie `false` może mimo wszytko skutkować ponownym zrenderowaniem komponentu. * * * @@ -274,22 +274,22 @@ Currently, if `shouldComponentUpdate()` returns `false`, then [`UNSAFE_component static getDerivedStateFromProps(props, state) ``` -`getDerivedStateFromProps` is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing. +Metoda `getDerivedStateFromProps` jest wywoływana zaraz przed wywołaniem metody render, zarówno przy początkowym montowaniu, jak i przy dalszych aktualizacjach. Powinna zwrócić obiekt, aby zaktualizować stan, lub zwrócić null, aby nie aktualizować nic. -This method exists for [rare use cases](/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state) where the state depends on changes in props over time. For example, it might be handy for implementing a `` component that compares its previous and next children to decide which of them to animate in and out. +Ta metoda istnieje dla [rzadkich przypadków użycia](/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state), w których stan zależy od zmian właściwości w czasie. Na przykład, może okazać się przydatnym komponent ``, który porównuje swoje obecne komponenty potomne z poprzednimi, aby zdecydować, króre z nich mają pojawić się z animacją, a które zniknąć. -Deriving state leads to verbose code and makes your components difficult to think about. -[Make sure you're familiar with simpler alternatives:](/blog/2018/06/07/you-probably-dont-need-derived-state.html) +Derywowanie stanu sprawia, że kod jest rozwlekły i trudno myśli się o komponentach. +[Upewnij się, że znasz prostsze alternatywy:](/blog/2018/06/07/you-probably-dont-need-derived-state.html) -* If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) lifecycle instead. +* Jeśli potrzebujesz **spowodować efekt uboczny** (na przykład pobranie danych, albo animację) w odpowiedzi na zmianę właściwości, zamiast tego użyj metody cyklu życia [`componentDidUpdate`](#componentdidupdate). -* If you want to **re-compute some data only when a prop changes**, [use a memoization helper instead](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization). +* Jeśli chcesz **ponownie obliczyć pewne dane tylko, kiedy zmieni się właściwość**, [zamiast tego użyj pomocniczych technik memoizacyjnych](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization). -* If you want to **"reset" some state when a prop changes**, consider either making a component [fully controlled](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead. +* Jeśli chcesz **"zresetować" stan przy zmianie właściwości**, rozważ zamiast tego uczynienie komponentu [całkowicie kontrolowanym](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) lub [całkowicie niekontrolowanym z właściwością `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key). -This method doesn't have access to the component instance. If you'd like, you can reuse some code between `getDerivedStateFromProps()` and the other class methods by extracting pure functions of the component props and state outside the class definition. +Ta metoda nie ma dostępu do instancji komponentu. Jeśli chcesz, możesz używać ponownie kod pomiędzy `getDerivedStateFromProps()` innymi metodami klasy poprzez wyodrębnienie czystych funkcji właściwości i stanu komponentu poza definicję klasy. -Note that this method is fired on *every* render, regardless of the cause. This is in contrast to `UNSAFE_componentWillReceiveProps`, which only fires when the parent causes a re-render and not as a result of a local `setState`. +Zauważ, że metoda ta wywoływana jest przy *każdym* renderowaniu, bez względu na przyczynę. Jest to kontrastem dla metody `UNSAFE_componentWillReceiveProps`, która zostaje wywołana tylko, kiedy komponent nadrzędny powoduje ponowne zrenderowanie, a nie jako wynik lokalnego wywołania metody `setState`. * * * @@ -299,41 +299,41 @@ Note that this method is fired on *every* render, regardless of the cause. This getSnapshotBeforeUpdate(prevProps, prevState) ``` -`getSnapshotBeforeUpdate()` is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle will be passed as a parameter to `componentDidUpdate()`. +Metoda `getSnapshotBeforeUpdate()` jest wywoływana zaraz przed tym, gdy ostatnio zrenderowany wynik zostaje zatwierdzony do np. drzewa DOM. Pozwala to twojemu komponentowi na przejęcie pewnych informacji z drzewa DOM (np. pozycje scrolla) przed ich potencjalną zmianą. Każda wartość zwrócona przez metodę cyklu życia zostanie przekazana jako parametr do metody `componentDidUpdate()`. -This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way. +Ten przypadek użycia nie jest częsty, ale może wystąpić w interfejsach użytkownika takich jak wątki czatu, które potrzebują możliwości zarządzania pozycją scrolla w specjalny sposób. -A snapshot value (or `null`) should be returned. +Powinna być zwrócona wartość snapshotu (lub `null`). -For example: +Dla przykładu: `embed:react-component-reference/get-snapshot-before-update.js` -In the above examples, it is important to read the `scrollHeight` property in `getSnapshotBeforeUpdate` because there may be delays between "render" phase lifecycles (like `render`) and "commit" phase lifecycles (like `getSnapshotBeforeUpdate` and `componentDidUpdate`). +W powyższych przykładach, ważne jest odczytanie własności `scrollHeight` w metodzie `getSnapshotBeforeUpdate`, ponieważ mogą wystąpić opóźnienia pomiędzy metodami cyklu życia w fazie "render" (takimi jak `render`), a metodami fazy "commit" (takimi jak `getSnapshotBeforeUpdate` i `componentDidUpdate`). * * * -### Error boundaries {#error-boundaries} +### Granice błędów {#error-boundaries} -[Error boundaries](/docs/error-boundaries.html) are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. +[Granice błędów](/docs/error-boundaries.html) to reactowe komponenty, które wychwytują javascriptowe wyjątki w dowolnych miejscach swojego drzewa komponentów potomnych, zapisują te wyjątki, i pokazują awaryjny interfejs użytkownika zamiast drzewa komponentów, które rzuciło tym wyjątkiem. Granice błędów wychwytują wyjątki podczas renderowania, w metodach cyklu życia, i w konstruktorach całego drzewa potomnego. -A class component becomes an error boundary if it defines either (or both) of the lifecycle methods `static getDerivedStateFromError()` or `componentDidCatch()`. Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI. +Komponent klasowy staje się granicą błędu, jeśli ma zdefiniowaną jedną z (lub obie) metod cyklu życia `static getDerivedStateFromError()` lub `componentDidCatch()`. Aktualizacja stanu z tych metod pozwala na wychwycenie nieobsłużonego javascriptowego wyjątku w drzewie komponentów potomnych i pokazać rezerwowy interfejs użytkownika. -Only use error boundaries for recovering from unexpected exceptions; **don't try to use them for control flow.** +Używaj granic błędów tylko do rekonwalescencji po nieoczekiwanych wyjątkach; **nie próbuj używać ich do kontrolowania przebiegu programu.** -For more details, see [*Error Handling in React 16*](/blog/2017/07/26/error-handling-in-react-16.html). +Po więcej szczegółów, odwiedź [*Obsługa wyjątków w Reakcie 16*](/blog/2017/07/26/error-handling-in-react-16.html). -> Note +> Uwaga > -> Error boundaries only catch errors in the components **below** them in the tree. An error boundary can’t catch an error within itself. +> Granice błędów wychwytują tylko wyjątki w komponentach z drzewa **pod** nimi. Granica błędów nie może wychwycić wyjątku, który wystąpił w niej samej. ### `static getDerivedStateFromError()` {#static-getderivedstatefromerror} ```javascript static getDerivedStateFromError(error) ``` -This lifecycle is invoked after an error has been thrown by a descendant component. -It receives the error that was thrown as a parameter and should return a value to update state. +Ta metoda cyklu życia jest wywoływana po wyrzuceniu wyjątku przez komponent potomny. +Wyrzucony wyjątek zostaje do niej przekazany jako argument, jej wynikiem powinna być wartość, która pozwoli na zaktualizowanie stanu. ```js{7-10,13-16} class ErrorBoundary extends React.Component { @@ -343,25 +343,25 @@ class ErrorBoundary extends React.Component { } static getDerivedStateFromError(error) { - // Update state so the next render will show the fallback UI. + // Aktualizacja stanu, aby kolejne zrenderowanie pokazało awaryjny interfejs użytkownika. return { hasError: true }; } render() { if (this.state.hasError) { - // You can render any custom fallback UI + // Możesz zrenderować dowolny spersonalizowany interfejs użytkownika return

Something went wrong.

; } - return this.props.children; + return this.props.children; } } ``` -> Note +> Uwaga > -> `getDerivedStateFromError()` is called during the "render" phase, so side-effects are not permitted. -For those use cases, use `componentDidCatch()` instead. +> Metoda `getDerivedStateFromError()` jest wywoływana podczas fazy "render", więc nie są w niej dozwolone skutki uboczne. +Zamiast tego, dla tych przypadków użycia użyj metody `componentDidCatch()`. * * * @@ -371,15 +371,15 @@ For those use cases, use `componentDidCatch()` instead. componentDidCatch(error, info) ``` -This lifecycle is invoked after an error has been thrown by a descendant component. -It receives two parameters: +Ta metoda cyklu życia jest wywoływana po wyrzuceniu wyjątku przez komponent potomny. +Otrzymuje on dwa argumenty: -1. `error` - The error that was thrown. -2. `info` - An object with a `componentStack` key containing [information about which component threw the error](/docs/error-boundaries.html#component-stack-traces). +1. `error` - Wyjątek, który został wyrzucony. +2. `info` - Obiekt z kluczem `componentStack` zawierający [informację o tym, który komponent wyrzucił ten wyjątek](/docs/error-boundaries.html#component-stack-traces). -`componentDidCatch()` is called during the "commit" phase, so side-effects are permitted. -It should be used for things like logging errors: +Metoda `componentDidCatch()` jest wywoływana w fazie "commit", więc dozwolone są w niej skutki uboczne. +Powinna być używana do czynności takich jak zapisywanie błędów: ```js{12-19} class ErrorBoundary extends React.Component { @@ -389,12 +389,12 @@ class ErrorBoundary extends React.Component { } static getDerivedStateFromError(error) { - // Update state so the next render will show the fallback UI. + // Aktualizacja stanu, aby kolejne zrenderowanie pokazało awaryjny interfejs użytkownika. return { hasError: true }; } componentDidCatch(error, info) { - // Example "componentStack": + // Przykładowy "componentStack": // in ComponentThatThrows (created by App) // in ErrorBoundary (created by App) // in div (created by App) @@ -404,8 +404,8 @@ class ErrorBoundary extends React.Component { render() { if (this.state.hasError) { - // You can render any custom fallback UI - return

Something went wrong.

; + // Możesz zrenderować dowolny spersonalizowany interfejs użytkownika + return

Coś poszło nie tak.

; } return this.props.children; @@ -413,16 +413,16 @@ class ErrorBoundary extends React.Component { } ``` -> Note +> Uwaga > -> In the event of an error, you can render a fallback UI with `componentDidCatch()` by calling `setState`, but this will be deprecated in a future release. -> Use `static getDerivedStateFromError()` to handle fallback rendering instead. +> W razie wyjątku, możesz zrenderować awaryjny interfejs użytkownika za pomocą metody `componentDidCatch()` poprzez wywołanie metody `setState`, ale możliwość ta będzie przestarzała w przyszłych wersjach. +> Do obsługi renderowania awaryjnego używaj zamiast tego metody `static getDerivedStateFromError()`. * * * -### Legacy Lifecycle Methods {#legacy-lifecycle-methods} +### Przestarzałe metody cyklu życia {#legacy-lifecycle-methods} -The lifecycle methods below are marked as "legacy". They still work, but we don't recommend using them in the new code. You can learn more about migrating away from legacy lifecycle methods in [this blog post](/blog/2018/03/27/update-on-async-rendering.html). +Poniższe metody cyklu życia są oznaczone jako "przestarzałe". Wciąż działają, zalecamy jednak nie używać ich w nowym kodzie. Możesz dowiedzieć się więcej o migracji od przestarzałych metod cyklu życia [w tym wpisie na blogu](/blog/2018/03/27/update-on-async-rendering.html). ### `UNSAFE_componentWillMount()` {#unsafe_componentwillmount} @@ -430,15 +430,15 @@ The lifecycle methods below are marked as "legacy". They still work, but we don' UNSAFE_componentWillMount() ``` -> Note +> Uwaga > -> This lifecycle was previously named `componentWillMount`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +> Ta metoda cyklu życia była wcześniej nazwana `componentWillMount`. Ta nazwa będzie działać do wersji 17. Użyj [codemoda `rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), aby automatycznie zaktualizować swoje komponenty. -`UNSAFE_componentWillMount()` is invoked just before mounting occurs. It is called before `render()`, therefore calling `setState()` synchronously in this method will not trigger an extra rendering. Generally, we recommend using the `constructor()` instead for initializing state. +Metoda `UNSAFE_componentWillMount()` jest wywoływana zaraz przed nastąpieniem montowania. Jest wywoływana przed `render()`, zatem synchroniczne wywoływanie `setState()` w tej metodzie nie spowoduje dodatkowego renderowania. Generalnie, zamiast tego do inicjalizacji stanu zalecamy używania konstruktora. -Avoid introducing any side-effects or subscriptions in this method. For those use cases, use `componentDidMount()` instead. +Unikaj wprowadzania skutków ubocznych lub inicjalizowania subskrypcji w tej metodzie. Dla tych przypadków użycia, używaj zamiast tego metody `componentDidMount()`. -This is the only lifecycle method called on server rendering. +Jest to jedyna metoda cyklu życia wywoływana przy renderowaniu na serwerze. * * * @@ -448,25 +448,25 @@ This is the only lifecycle method called on server rendering. UNSAFE_componentWillReceiveProps(nextProps) ``` -> Note +> Uwaga > -> This lifecycle was previously named `componentWillReceiveProps`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +> Ta metoda cyklu życia była wcześniej nazwana `componentWillReceiveProps`. Ta nazwa będzie działać do wersji 17. Użyj [codemoda `rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), aby automatycznie zaktualizować swoje komponenty. -> Note: +> Uwaga: > -> Using this lifecycle method often leads to bugs and inconsistencies +> Używanie tej metody cyklu życia często prowadzi do błędów i niespójności > -> * If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) lifecycle instead. -> * If you used `componentWillReceiveProps` for **re-computing some data only when a prop changes**, [use a memoization helper instead](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization). -> * If you used `componentWillReceiveProps` to **"reset" some state when a prop changes**, consider either making a component [fully controlled](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead. +> * Jeśli potrzebujesz **wykonać efekt uboczny** (na przykład, pobieranie danych lub animację) w odpowiedzi na zmianę właściwości, zamiast tego użyj metody cyklu życia [`componentDidUpdate`](#componentdidupdate). +> * Jeśli używałeś `componentWillReceiveProps` do **ponownego obliczania pewnych danych tylko w przypadku zmiany właściwości**, [zamiast tego użyj pomocniczych technik memoizacyjnych](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization). +> * Jeśli używałeś `componentWillReceiveProps` do **"resetowania" stanu w przypadku zmiany właściwości**, zamiast tego rozważ uczynienie komponentu [całkowicie kontrolowanym](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) lub [całkowicie niekontrolowanym z właściwością `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key). > -> For other use cases, [follow the recommendations in this blog post about derived state](/blog/2018/06/07/you-probably-dont-need-derived-state.html). +> Dla innych przypadków użycia, [śledź rekomendacje w tym wpisie na blogu na temat stanu pochodnego](/blog/2018/06/07/you-probably-dont-need-derived-state.html). -`UNSAFE_componentWillReceiveProps()` is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare `this.props` and `nextProps` and perform state transitions using `this.setState()` in this method. +Metoda `UNSAFE_componentWillReceiveProps()` jest wywoływana przed tym, jak zamontowany komponent otrzymuje nowe właściwości. Jeśli potrzebujesz zaktualizować stan w odpowiedzi na zmiany właściwości (na przykład, zresetować go), możesz porównać `this.props` i `nextProps` i wykonać przejście stanu w tej metodzie za pomocą `this.setState()`. -Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes. +Zauważ, że jeśli komponent nadrzędny powoduje ponowne zrenderowanie twojego komponentu, ta metoda będzie wywołana nawet jeśli właściwości nie uległy zmianie. Jeśli chcesz tylko obsłużyć zmiany, upewnij się, że porównujesz poprzednie i obecne wartości. -React doesn't call `UNSAFE_componentWillReceiveProps()` with initial props during [mounting](#mounting). It only calls this method if some of component's props may update. Calling `this.setState()` generally doesn't trigger `UNSAFE_componentWillReceiveProps()`. +React nie wywołuje metody `UNSAFE_componentWillReceiveProps()` z początkowymi właściwościami podczas [montowania](#mounting). Wywołuje ją tylko, kiedy właściwości któregoś z komponentów mogą zostać zaktualizowane. Wywołanie metody `this.setState()` przeważnie nie powoduje wywołania `UNSAFE_componentWillReceiveProps()`. * * * @@ -476,27 +476,27 @@ React doesn't call `UNSAFE_componentWillReceiveProps()` with initial props durin UNSAFE_componentWillUpdate(nextProps, nextState) ``` -> Note +> Uwaga > -> This lifecycle was previously named `componentWillUpdate`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +> Ta metoda cyklu życia była wcześniej nazwana `componentWillUpdate`. Ta nazwa będzie działać do wersji 17. Użyj [codemoda `rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), aby automatycznie zaktualizować swoje komponenty. -`UNSAFE_componentWillUpdate()` is invoked just before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render. +Metoda `UNSAFE_componentWillUpdate()` jest wywoływana zaraz przed renderowaniem, kiedy komponent uzyskuje nowe właściwości lub stan. Używaj tego jako okazji do przygotowania przed nastąpieniem aktualizacji. Ta metoda nie jest wywoływana przy początkowym renderowaniu. -Note that you cannot call `this.setState()` here; nor should you do anything else (e.g. dispatch a Redux action) that would trigger an update to a React component before `UNSAFE_componentWillUpdate()` returns. +Zauważ, że nie możesz tutaj wywołać `this.setState()`; nie powinieneś też robić niczego innego (np. wysyłania Reduxowych akcji), co spowodowałoby aktualizację reactowego komponentu przed powrotem z metody `UNSAFE_componentWillUpdate()`. -Typically, this method can be replaced by `componentDidUpdate()`. If you were reading from the DOM in this method (e.g. to save a scroll position), you can move that logic to `getSnapshotBeforeUpdate()`. +Metoda ta, zazwyczaj może być zastąpiona metodą `componentDidUpdate()`. Jeśli zczytywałeś w tej metodzie informacje z drzewa DOM (np. żeby zapisać pozycje scrolla), możesz przenieść tą logikę do getSnapshotBeforeUpdate(). -> Note +> Uwaga > -> `UNSAFE_componentWillUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false. +> Metoda `UNSAFE_componentWillUpdate()` nie będzie wywołana jeśli [`shouldComponentUpdate()`](#shouldcomponentupdate) zwróci `false`. * * * -## Other APIs {#other-apis-1} +## Inne API {#other-apis-1} -Unlike the lifecycle methods above (which React calls for you), the methods below are the methods *you* can call from your components. +W przeciwieństwie do metod cyklu życia powyżej (które wywołuje dla ciebie React), metody poniżej możesz wywołać *ty* ze swoich komponentów. -There are just two of them: `setState()` and `forceUpdate()`. +Są tylko dwie takie metody: `setState()` i `forceUpdate()`. ### `setState()` {#setstate} @@ -504,21 +504,21 @@ There are just two of them: `setState()` and `forceUpdate()`. setState(updater[, callback]) ``` -`setState()` enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses. +`setState()` ustawia w kolejce zmiany stanu komponentu i daje znać Reactowi, że komponent i jego komponenty potomne powinny zostać ponownie zrenderowane ze zaktualizowanym stanem. Jest to podstawowa metoda używana do aktualizacji interfejsu użytkownika w odpowiedzi na procedury obsługi zdarzeń i odpowiedzi z serwera. -Think of `setState()` as a *request* rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. +Myśl o metodzie `setState()` bardziej jako o *prośbie* niż o natychmiastowym poleceniu aktualizacji komponentu. Dla lepszej postrzeganej wydajności, React może ją opóźnić, a potem zaktualizować kilka komponentów za jednym zamachem. React nie gwarantuje natychmiastowego zastosowania zmian stanu. -`setState()` does not always immediately update the component. It may batch or defer the update until later. This makes reading `this.state` right after calling `setState()` a potential pitfall. Instead, use `componentDidUpdate` or a `setState` callback (`setState(updater, callback)`), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the `updater` argument below. +Metoda `setState()` nie zawsze od razu aktualizuje komponent. Może ona złączyć lub odłożyć aktualizację na później. Sprawia to, że odczytywanie `this.state` zaraz po wywołaniu `setState()` jest potencjalną pułapką. Zamiast tego, użyj metody `componentDidUpdate` lub funkcji zwrotnej (ang. *callback*) `setState` (`setState(updater, callback)`), które są wywoływane po zastosowaniu aktualizacji. Jeśli potrzebujesz zmienić stan w oparciu o poprzedni stan, zapoznaj się z poniższym argumentem `updater`. -`setState()` will always lead to a re-render unless `shouldComponentUpdate()` returns `false`. If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders. +`setState()` zawsze prowadzi do ponownego zrenderowanie, jeśli `shouldComponentUpdate()` zwróci `false`. Jeśli używane są zmienne obiekty lub warunkowa logika renderowania nie może być zaimplementowana w metodzie `shouldComponentUpdate()`, niepotrzebnego ponownego renderowania można uniknąć wywołując `setState()` tylko, kiedy nowy stan różni się od poprzedniego. -The first argument is an `updater` function with the signature: +Pierwszym argumentem jest funkcja `updater` posiadająca poniższą sygnaturę: ```javascript (state, props) => stateChange ``` -`state` is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from `state` and `props`. For instance, suppose we wanted to increment a value in state by `props.step`: +`state` jest referencją stanu komponentu w momencie, w którym zmiana zostaje zastosowana. Nie powinien on być bezpośrednio zmieniany. Zamiast tego, zmiany powinny być reprezentowane poprzez zbudowanie nowego obiektu na podstawie `state` and `props`. Na przykład załóżmy, że chcemy powiększyć pewną wartość w stanie o `props.step`: ```javascript this.setState((state, props) => { @@ -526,23 +526,23 @@ this.setState((state, props) => { }); ``` -Both `state` and `props` received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with `state`. +Zarówno `state`, jak i `props` otrzymywane przez funkcję aktualizującą są aktualne. Wynik aktualizatora zostaje płytko scalony ze stanem. -The second parameter to `setState()` is an optional callback function that will be executed once `setState` is completed and the component is re-rendered. Generally we recommend using `componentDidUpdate()` for such logic instead. +Drugi parametrem metody `setState()` jest opcjonalna funkcja zwrotna, która zostanie wywołana kiedy `setState` ukończy swój przebieg i komponent zostanie ponownie zrenderowany. Ogólnie rzecz biorąc, do tego typu logiki zalecamy zamiast tego używać metody `componentDidUpdate()`. -You may optionally pass an object as the first argument to `setState()` instead of a function: +Opcjonalnie, jako pierwszy argument do metody `setState()` zamiast funkcji możesz przekazać obiekt: ```javascript setState(stateChange[, callback]) ``` -This performs a shallow merge of `stateChange` into the new state, e.g., to adjust a shopping cart item quantity: +Powoduje to przeprowadzenie płytkiego scalenia argumentu `stateChange` do nowego stanu, np., w celu dostosowania ilości przedmiotów w koszyku: ```javascript this.setState({quantity: 2}) ``` -This form of `setState()` is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of: +Ta forma metody `setState()` także jest asynchroniczna, a wywołanie jej wiele razy podczas jednego cyklu może spowodować ich złączenie. Na przykład, jeśli spróbujesz zwiększyć ilość przedmiotów więcej niż jeden raz w tym samym cyklu, rezultatem tego będzie ekwiwalent: ```javaScript Object.assign( @@ -553,7 +553,7 @@ Object.assign( ) ``` -Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead: +Następujące wywołania nadpiszą wartości z poprzednich w tym samym cyklu, więc ilość będzie zwiększona tylko raz. Jeśli kolejny stan zależy od poprzedniego, zamiast tego zalecamy używania formy z funkcją aktualizującą: ```js this.setState((state) => { @@ -561,11 +561,11 @@ this.setState((state) => { }); ``` -For more detail, see: +Po więcej szczegółów, odwiedź: -* [State and Lifecycle guide](/docs/state-and-lifecycle.html) -* [In depth: When and why are `setState()` calls batched?](https://stackoverflow.com/a/48610973/458193) -* [In depth: Why isn't `this.state` updated immediately?](https://github.com/facebook/react/issues/11527#issuecomment-360199710) +* [Przewodnik po stanie i cyklu życia](/docs/state-and-lifecycle.html) +* [Dogłębnie: Kiedy i dlaczego wywołania `setState()` są łączone?](https://stackoverflow.com/a/48610973/458193) +* [Dogłębnie: Dlaczego this.state nie jest aktualizowany od razu?](https://github.com/facebook/react/issues/11527#issuecomment-360199710) * * * @@ -575,19 +575,19 @@ For more detail, see: component.forceUpdate(callback) ``` -By default, when your component's state or props change, your component will re-render. If your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`. +Domyślnie, kiedy zmienia się stan lub właściwości twojego komponentu, zrenderuje się on ponownie. Jeśli twoja metoda `render()` polega na innych danych, możesz powiadomić Reacta, że komponent potrzebuje ponownego zrenderowania, poprzez wywołanie metody `forceUpdate()`. -Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes. +Wywołanie `forceUpdate()` spowoduje, że na komponencie zostanie wywołana metoda `render()`, z pominięciem metody `shouldComponentUpdate()`. Spowoduje to wywołanie normalnych metod cyklu życia komponentów potomnych, włączając w to metodę `shouldComponentUpdate()` każdego z nich. React wciąż zaktualizuje drzewo DOM tylko w wypadku zmiany znaczników. -Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. +Przeważnie powinieneś unikać jakichkolwiek form użycia `forceUpdate()` i odczytywać dane jedynie z `this.props` i `this.state` w metodzie `render()`. * * * -## Class Properties {#class-properties-1} +## Właściwości Klasy {#class-properties-1} ### `defaultProps` {#defaultprops} -`defaultProps` can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example: +`defaultProps` może być zdefiniowana jako własność na samej klasie komponentu, aby ustawić domyślne właściwości dla tej klasy. Jest ona używana dla właściwości równych `undefined`, ale nie `null`. Dla przykładu: ```js class CustomButton extends React.Component { @@ -599,19 +599,19 @@ CustomButton.defaultProps = { }; ``` -If `props.color` is not provided, it will be set by default to `'blue'`: +Jeśli `props.color` nie jest podany, zostanie domyślnie ustawiony na `'blue'`: ```js render() { - return ; // props.color will be set to blue + return ; // props.color zostanie ustawiony na blue } ``` -If `props.color` is set to null, it will remain null: +Jeśli `props.color` zostanie ustawiony jako `null`, pozostanie nim: ```js render() { - return ; // props.color will remain null + return ; // props.color pozostanie równy null } ``` @@ -619,24 +619,24 @@ If `props.color` is set to null, it will remain null: ### `displayName` {#displayname} -The `displayName` string is used in debugging messages. Usually, you don't need to set it explicitly because it's inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see [Wrap the Display Name for Easy Debugging](/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging) for details. +Napis `displayName` jest używany w komunikatach debugowania. Przeważnie, nie musisz jawnie go definiować, ponieważ jest on wywnioskowany z nazwy funkcji lub klasy, w której zdefiniowany jest ten komponent. Możesz chcieć jawnie go zdefiniować, jeśli chcesz wyświetlić inną nazwę komponentu przy debugowaniu lub kiedy stworzysz komponent wyższego rzędu, po szczegóły odwiedź [Owiń nazwę wyświetlenia dla łatwego debugowania](/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging). * * * -## Instance Properties {#instance-properties-1} +## Właściwości instancji {#instance-properties-1} ### `props` {#props} -`this.props` contains the props that were defined by the caller of this component. See [Components and Props](/docs/components-and-props.html) for an introduction to props. +`this.props` zawiera właściwości, które zostały zdefiniowane przez przywołującego tego komponentu. Po wprowadzenie do właściwości, odwiedź [Komponenty i właściwości](/docs/components-and-props.html). -In particular, `this.props.children` is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself. +W szczególności, `this.props.children` jest specjalną właściwością, zazwyczaj zdefiniowaną poprzez potomne tagi w wyrażeniu JSX, a nie w samym tagu instancji. ### `state` {#state} -The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object. +Stan zawiera dane specyficzne dla tego komponentu, które mogą zmieniać się w czasie. Stan jest definiowany przez użytkownika i powinien być zwykłym javascriptowym obiektem. -If some value isn't used for rendering or data flow (for example, a timer ID), you don't have to put it in the state. Such values can be defined as fields on the component instance. +Jeśli jakaś wartość nie jest używana do renderowania ani przepływu danych (na przykład, ID licznika czasu), nie musisz umieszczać jej w stanie. Wartości tego typu mogą być zdefiniowane jako pola składowe instancji komponentu. -See [State and Lifecycle](/docs/state-and-lifecycle.html) for more information about the state. +Po informacje na temat stanu, odwiedź [Stan i cykl życia](/docs/state-and-lifecycle.html). -Never mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable. +Nigdy nie zmieniaj `this.state` bezpośrednio, gdyż późniejsze wywołanie `setState()` może zastąpić wykonaną przez ciebie zmianę. Traktuj `this.state` jako niezmienny. diff --git a/examples/react-component-reference/get-snapshot-before-update.js b/examples/react-component-reference/get-snapshot-before-update.js index cf1fb2335..e2c367f23 100644 --- a/examples/react-component-reference/get-snapshot-before-update.js +++ b/examples/react-component-reference/get-snapshot-before-update.js @@ -5,8 +5,8 @@ class ScrollingList extends React.Component { } getSnapshotBeforeUpdate(prevProps, prevState) { - // Are we adding new items to the list? - // Capture the scroll position so we can adjust scroll later. + // Czy dodajemy nowe pozycje do listy? + // Przechowajmy pozycję scrolla, aby móc dostosować ją później. if (prevProps.list.length < this.props.list.length) { const list = this.listRef.current; return list.scrollHeight - list.scrollTop; @@ -15,9 +15,9 @@ class ScrollingList extends React.Component { } componentDidUpdate(prevProps, prevState, snapshot) { - // If we have a snapshot value, we've just added new items. - // Adjust scroll so these new items don't push the old ones out of view. - // (snapshot here is the value returned from getSnapshotBeforeUpdate) + // Jeśli mamy snapshot, to znaczy, że właśnie dodaliśmy nowe pozycje. + // Dopasujmy scroll, aby te nowe pozycje nie wypchnęły starych z widoku. + // (snapshot jest tutaj wartością zwróconą z metody getSnapshotBeforeUpdate) if (snapshot !== null) { const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; @@ -26,7 +26,7 @@ class ScrollingList extends React.Component { render() { return ( -
{/* ...contents... */}
+
{/* ...zawartość... */}
); } } From f8408e70196836558a54ff25f92b33bf7f331e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:18:43 +0200 Subject: [PATCH 2/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index 9b40c983c..50cc29922 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -15,7 +15,7 @@ redirect_from: - "tips/use-react-with-other-libraries.html" --- -Ta strona zawiera szegółowe odniesienie do definicji klasy reactowego komponentu. Zakłada ona, że znasz fundamentalne zagadnienia Reacta, takie jak [Komponenty i właściwości](/docs/components-and-props.html), i [Stan i cykl życia](/docs/state-and-lifecycle.html). Jeśli nie, zapoznaj się najpierw z nimi. +Ta strona zawiera szegółowe odniesienie do definicji klasy reactowego komponentu. Zakłada ona, że znasz fundamentalne zagadnienia Reacta, takie jak [komponenty i właściwości](/docs/components-and-props.html), i [stan i cykl życia](/docs/state-and-lifecycle.html). Jeśli nie, zapoznaj się najpierw z nimi. ## Ogólne informacje {#overview} From 3fa701ee2dabaf6e22a879b8c633a2deca65211f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:19:07 +0200 Subject: [PATCH 3/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index 50cc29922..a8ccb74d7 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -109,7 +109,7 @@ Każdy komponent zapewnia też kilka innych API: ### Powszechnie używane metody cyklu życia {#commonly-used-lifecycle-methods} -Metody opisane w tym rozdziale pokrywają zdecydowaną większość przypadków użycia, na które natkniesz się tworząc reactowe komponenty. **Dla odniesienia wizualnego, zobacz [ten diagram cyklu życia](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).** +Metody opisane w tym rozdziale pokrywają zdecydowaną większość przypadków użycia, na które natkniesz się tworząc reactowe komponenty. **Dla wizualnego odniesienia, zobacz [ten diagram cyklu życia](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).** ### `render()` {#render} From 2788897b6b76fbc48d16bb1f3a2715a81759d568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:20:12 +0200 Subject: [PATCH 4/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index a8ccb74d7..1b59f0581 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -301,7 +301,7 @@ getSnapshotBeforeUpdate(prevProps, prevState) Metoda `getSnapshotBeforeUpdate()` jest wywoływana zaraz przed tym, gdy ostatnio zrenderowany wynik zostaje zatwierdzony do np. drzewa DOM. Pozwala to twojemu komponentowi na przejęcie pewnych informacji z drzewa DOM (np. pozycje scrolla) przed ich potencjalną zmianą. Każda wartość zwrócona przez metodę cyklu życia zostanie przekazana jako parametr do metody `componentDidUpdate()`. -Ten przypadek użycia nie jest częsty, ale może wystąpić w interfejsach użytkownika takich jak wątki czatu, które potrzebują możliwości zarządzania pozycją scrolla w specjalny sposób. +Ten przypadek użycia nie jest powszechny, ale może wystąpić w interfejsach użytkownika takich jak wątki czatu, które potrzebują możliwości zarządzania pozycją scrolla w specjalny sposób. Powinna być zwrócona wartość snapshotu (lub `null`). From 96e332a8ba5a01af9256fc7135058c507c9c7661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:20:56 +0200 Subject: [PATCH 5/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index 1b59f0581..06750dc24 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -349,7 +349,7 @@ class ErrorBoundary extends React.Component { render() { if (this.state.hasError) { - // Możesz zrenderować dowolny spersonalizowany interfejs użytkownika + // Możesz zrenderować dowolny awaryjny interfejs użytkownika return

Something went wrong.

; } From 4fa5e50f4a637b45b65b6613ec0117d5d2008afe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:21:20 +0200 Subject: [PATCH 6/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index 06750dc24..e83a64b26 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -404,7 +404,7 @@ class ErrorBoundary extends React.Component { render() { if (this.state.hasError) { - // Możesz zrenderować dowolny spersonalizowany interfejs użytkownika + // Możesz zrenderować dowolny awaryjny interfejs użytkownika return

Coś poszło nie tak.

; } From f6347bb3ea64517c3c077efc185a83b1d4c2df42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:23:54 +0200 Subject: [PATCH 7/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index e83a64b26..0b7ddc416 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -313,7 +313,7 @@ W powyższych przykładach, ważne jest odczytanie własności `scrollHeight` w * * * -### Granice błędów {#error-boundaries} +### Granice błędu {#error-boundaries} [Granice błędów](/docs/error-boundaries.html) to reactowe komponenty, które wychwytują javascriptowe wyjątki w dowolnych miejscach swojego drzewa komponentów potomnych, zapisują te wyjątki, i pokazują awaryjny interfejs użytkownika zamiast drzewa komponentów, które rzuciło tym wyjątkiem. Granice błędów wychwytują wyjątki podczas renderowania, w metodach cyklu życia, i w konstruktorach całego drzewa potomnego. From 840a53df25f2c0879ab7258d076580081dd37f21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20=C5=BBuber?= Date: Sun, 14 Apr 2019 11:25:22 +0200 Subject: [PATCH 8/8] Update content/docs/reference-react-component.md Co-Authored-By: arekmaz --- content/docs/reference-react-component.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md index 0b7ddc416..05dde6d0e 100644 --- a/content/docs/reference-react-component.md +++ b/content/docs/reference-react-component.md @@ -264,7 +264,7 @@ Jeśli jesteś pewny, że chcesz ją napisać własnoręcznie, możesz porówna Nie zalecamy wykonywania głębokich porównań lub używania `JSON.stringify()` w metodzie `shouldComponentUpdate()`. Jest to bardzo nieefektywne i negatywnie odbije się na wydajności. -Obecnie, jeśli `shouldComponentUpdate()` zwróci `false`, [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render) i [`componentDidUpdate()`](#componentdidupdate) nie zostana wywołane. W przyszłosci React może traktować `shouldComponentUpdate()` jako wskazówkę, a nie jako ścisłą dyrektywę, a zwrócenie `false` może mimo wszytko skutkować ponownym zrenderowaniem komponentu. +Obecnie, jeśli `shouldComponentUpdate()` zwróci `false`, [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render) i [`componentDidUpdate()`](#componentdidupdate) nie zostana wywołane. W przyszłosci React może traktować `shouldComponentUpdate()` jako wskazówkę, a nie jako ścisłą dyrektywę, a zwrócenie `false` może mimo wszytko skutkować ponownym wyrenderowaniem komponentu. * * *