diff --git a/content/docs/state-and-lifecycle.md b/content/docs/state-and-lifecycle.md index e3ddafa28..839a15750 100644 --- a/content/docs/state-and-lifecycle.md +++ b/content/docs/state-and-lifecycle.md @@ -1,6 +1,6 @@ --- id: state-and-lifecycle -title: State and Lifecycle +title: Állapot és életciklus permalink: docs/state-and-lifecycle.html redirect_from: - "docs/interactivity-and-dynamic-uis.html" @@ -8,16 +8,16 @@ prev: components-and-props.html next: handling-events.html --- -This page introduces the concept of state and lifecycle in a React component. You can find a [detailed component API reference here](/docs/react-component.html). +Ez az oldal az állapot és életciklus fogalmait mutatja be egy React komponensben. A [részletes komponens API referenciát itt](/docs/react-component.html) találod. -Consider the ticking clock example from [one of the previous sections](/docs/rendering-elements.html#updating-the-rendered-element). In [Rendering Elements](/docs/rendering-elements.html#rendering-an-element-into-the-dom), we have only learned one way to update the UI. We call `ReactDOM.render()` to change the rendered output: +Vedd a ketyegő óra példát [az egyik korábbi fejezetből](/docs/rendering-elements.html#updating-the-rendered-element). Az [Elemek renderelése](/docs/rendering-elements.html#rendering-an-element-into-the-dom) fejezetben csak egyetlen módját tanultuk meg a felhasználói felület frissítésének. A `ReactDOM.render()` metódus meghívásával megváltoztatjuk a renderelt kimenetet: ```js{8-11} function tick() { const element = (
-

Hello, world!

-

It is {new Date().toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {new Date().toLocaleTimeString()}.

); ReactDOM.render( @@ -29,18 +29,18 @@ function tick() { setInterval(tick, 1000); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwoJZk?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/gwoJZk?editors=0010) -In this section, we will learn how to make the `Clock` component truly reusable and encapsulated. It will set up its own timer and update itself every second. +Ebben a fejezetben megtanuljuk, hogy hogyan tudjuk a `Clock` komponenst igazán újrafelhasználhatóvá és egységbe foglalttá tenni. Saját időzítőt fog beállítani, hogy minden másodpercben frissíteni tudja önmagát. -We can start by encapsulating how the clock looks: +Kezdhetjük azzal, hogy hogyan foglaljuk egységbe azt, ahogyan az óra kinéz: ```js{3-6,12} function Clock(props) { return (
-

Hello, world!

-

It is {props.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {props.date.toLocaleTimeString()}.

); } @@ -55,11 +55,11 @@ function tick() { setInterval(tick, 1000); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010) -However, it misses a crucial requirement: the fact that the `Clock` sets up a timer and updates the UI every second should be an implementation detail of the `Clock`. +Azonban ebből hiányzik valami nagyon fontos: Az a tény, hogy a `Clock` komponens beállít egy időzítőt és minden másodpercben frissíti a felhasználói felületet, a `Clock` komponens saját implementációs részlete kell hogy legyen. -Ideally we want to write this once and have the `Clock` update itself: +Ideális esetben ezt egyszer szeretnénk megírni és hagyjuk a `Clock`-ot saját magát frissíteni: ```js{2} ReactDOM.render( @@ -68,63 +68,63 @@ ReactDOM.render( ); ``` -To implement this, we need to add "state" to the `Clock` component. +Ennek az implementálásához szükségünk lesz egy "állapot"-ra ("state") a `Clock` komponensben. -State is similar to props, but it is private and fully controlled by the component. +Az állapot hasonló a prop-okhoz, de privát a komponensre nézve, és teljes mértékben irányított a komponens által. -## Converting a Function to a Class {#converting-a-function-to-a-class} +## Függvény konvertálása osztállyá {#converting-a-function-to-a-class} -You can convert a function component like `Clock` to a class in five steps: +Egy függvény komponenst, mint például a `Clock`-ot, ebben az öt lépésben tudsz osztállyá konvertálni: -1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), with the same name, that extends `React.Component`. +1. Készíts egy [ES6 osztályt](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) ugyanazzal a névvel és terjeszd ki a `React.Component` osztályt. -2. Add a single empty method to it called `render()`. +2. Adj hozzá egy üres `render()` metódust. -3. Move the body of the function into the `render()` method. +3. Helyezd át a a függvény testét a `render()` metódusba. -4. Replace `props` with `this.props` in the `render()` body. +4. Nevezd át a `props`-ot `this.props`-ra a `render()` testében. -5. Delete the remaining empty function declaration. +5. Töröld a megmaradt üres függvény deklarációt. ```js class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.props.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.props.date.toLocaleTimeString()}.

); } } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) -`Clock` is now defined as a class rather than a function. +A `Clock` most már osztályként van definiálva függvény helyett. -The `render` method will be called each time an update happens, but as long as we render `` into the same DOM node, only a single instance of the `Clock` class will be used. This lets us use additional features such as local state and lifecycle methods. +A `render` metódus minden alkalommal meg lesz hívva ha egy frissítés történik, de amíg a ``-ot ugyanabba a DOM csomópontba rendereljük, addig a `Clock` osztálynak csupán egy példánya lesz használva. Ez lehetővé teszi olyan funkciók hozzáadását mint a helyi állapot és életciklus metódusok. -## Adding Local State to a Class {#adding-local-state-to-a-class} +## Helyi állapot hozzáadása egy osztályhoz {#adding-local-state-to-a-class} -We will move the `date` from props to state in three steps: +Helyezzük át a `date` objektumot a props-ból a state-be három lépésben: -1) Replace `this.props.date` with `this.state.date` in the `render()` method: +1) Nevezd át a `this.props.date`-et `this.state.date`-re a `render()` metódusban: ```js{6} class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.state.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.state.date.toLocaleTimeString()}.

); } } ``` -2) Add a [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor) that assigns the initial `this.state`: +2) Adj hozzá egy [osztály konstruktort](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor), ami hozzárendel egy kezdetleges `this.state`-et: ```js{4} class Clock extends React.Component { @@ -136,15 +136,15 @@ class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.state.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.state.date.toLocaleTimeString()}.

); } } ``` -Note how we pass `props` to the base constructor: +Figyeld meg, hogy hogyan adjuk át az alapkonstruktornak a `props`-ot: ```js{2} constructor(props) { @@ -153,9 +153,9 @@ Note how we pass `props` to the base constructor: } ``` -Class components should always call the base constructor with `props`. +Az osztálykomponensek konstruktorai mindig meg kell hogy hívják az alapkonstruktort a `props` átadásával. -3) Remove the `date` prop from the `` element: +3) Töröld ki a `date` prop-ot a `` elemből: ```js{2} ReactDOM.render( @@ -164,9 +164,9 @@ ReactDOM.render( ); ``` -We will later add the timer code back to the component itself. +Az időzítő kódját később adjuk vissza a komponensbe. -The result looks like this: +Az eredmény így néz ki: ```js{2-5,11,18} class Clock extends React.Component { @@ -178,8 +178,8 @@ class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.state.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.state.date.toLocaleTimeString()}.

); } @@ -191,19 +191,19 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010) -Next, we'll make the `Clock` set up its own timer and update itself every second. +A következőben hagyjuk, hogy a `Clock` maga állítson be egy időzítőt és frissítse magát minden másodpercben. -## Adding Lifecycle Methods to a Class {#adding-lifecycle-methods-to-a-class} +## Életciklus metódusok hozzáadása egy osztályhoz {#adding-lifecycle-methods-to-a-class} -In applications with many components, it's very important to free up resources taken by the components when they are destroyed. +Sok komponenssel rendelkező alkalmazásokban nagyon fontos, hogy a komponensek által elfoglalt erőforrásokat felszabadítsuk, amikor azok elpusztulnak. -We want to [set up a timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) whenever the `Clock` is rendered to the DOM for the first time. This is called "mounting" in React. +Szeretnénk [felállítani egy időzítőt](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval), amikor a `Clock` először renderelődik DOM-ba. A Reactben ezt hívjuk "előkészítés"-nek, vagy "mounting"-nak. -We also want to [clear that timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) whenever the DOM produced by the `Clock` is removed. This is called "unmounting" in React. +Azt is szeretnénk, ha az [időzítő törölve lenne](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval), amikor a DOM által készített `Clock` el lesz távolítva. A React-ben ezt hívjuk "leválasztás"-nak vagy "unmounting"-nak. -We can declare special methods on the component class to run some code when a component mounts and unmounts: +A komponens oszályban tudunk speciális metódusokat deklarálni, amik lefuttatnak egy kódot amikor a komponens előkészül, vagy leválik: ```js{7-9,11-13} class Clock extends React.Component { @@ -223,17 +223,17 @@ class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.state.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.state.date.toLocaleTimeString()}.

); } } ``` -These methods are called "lifecycle methods". +Ezeket a metódusokat "életciklus" metódusoknak" hívjuk. -The `componentDidMount()` method runs after the component output has been rendered to the DOM. This is a good place to set up a timer: +A `componentDidMount()` metódus azután fut le, hogy a komponens kimenete a DOM-ba lett renderelve. Ez egy jó hely az időzítő beállítására: ```js{2-5} componentDidMount() { @@ -244,11 +244,11 @@ The `componentDidMount()` method runs after the component output has been render } ``` -Note how we save the timer ID right on `this` (`this.timerID`). +Vedd észre, hogy az időzítő azonosítóját közvetlenül a `this`-re mentjük (`this.timerID`). -While `this.props` is set up by React itself and `this.state` has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID). +Míg a `this.props`-ot maga a React állítja fel, és a `this.state`-nek speciális jelentése van, te nyugodtan adhatsz hozzá manuálisan egyéb mezőket, ha valamit tárolni szeretnél, ami nem vesz részt az adatfolyamban (mint például az időzítő azonosító). -We will tear down the timer in the `componentWillUnmount()` lifecycle method: +Az időzítőt a `componentWillUnmount()` életciklus metódusban fogjuk leállítani: ```js{2} componentWillUnmount() { @@ -256,9 +256,9 @@ We will tear down the timer in the `componentWillUnmount()` lifecycle method: } ``` -Finally, we will implement a method called `tick()` that the `Clock` component will run every second. +Végezetül implementálni fogunk egy `tick()` metódust, amit a `Clock` komponens fog futtatni minden másodpercben. -It will use `this.setState()` to schedule updates to the component local state: +Ez a `this.setState()` metódus segítségével fogja a komponens helyi állapotát frissíteni. ```js{18-22} class Clock extends React.Component { @@ -287,8 +287,8 @@ class Clock extends React.Component { render() { return (
-

Hello, world!

-

It is {this.state.date.toLocaleTimeString()}.

+

Helló, világ!

+

Az idő {this.state.date.toLocaleTimeString()}.

); } @@ -300,72 +300,72 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) -Now the clock ticks every second. +Az óra most már minden másodpercben kettyen. -Let's quickly recap what's going on and the order in which the methods are called: +Vegyük át gyorsan mi is történik és a metódusok milyen sorrendben vannak meghívva: -1) When `` is passed to `ReactDOM.render()`, React calls the constructor of the `Clock` component. Since `Clock` needs to display the current time, it initializes `this.state` with an object including the current time. We will later update this state. +1) Amikor a ``-ot átadjuk a `ReactDOM.render()` metódusnak, a React meghívja a `Clock` komponens konstruktorát. Mivel a `Clock` komponensnek meg kell jelenítenie a jelenlegi időt, ez inicializál egy `this.state`-et, ami egy objektumot tartalmaz a jelenlegi idővel. Később ezt az állapotot frissítjük. -2) React then calls the `Clock` component's `render()` method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the `Clock`'s render output. +2) Ezután a React meghívja a `Clock` komponens `render()` metódusát. A React ennek segítségével állapítja meg, hogy mit kell mutatnia a képernyőn. A React ezután frissíti a DOM-ot, hogy az megegyezzen a `Clock` render kimenetével. -3) When the `Clock` output is inserted in the DOM, React calls the `componentDidMount()` lifecycle method. Inside it, the `Clock` component asks the browser to set up a timer to call the component's `tick()` method once a second. +3) Amikor a `Clock` kimenet be van illesztve a DOM-ba, a React meghívja a `componentDidMount()` életciklus metódust. Ezen belül a `Clock` komponens megkéri a böngészőt, hogy az állítson fel egy időzítőt, ami minden másodpercben meghívja a komponens `tick()` metódusát. -4) Every second the browser calls the `tick()` method. Inside it, the `Clock` component schedules a UI update by calling `setState()` with an object containing the current time. Thanks to the `setState()` call, React knows the state has changed, and calls the `render()` method again to learn what should be on the screen. This time, `this.state.date` in the `render()` method will be different, and so the render output will include the updated time. React updates the DOM accordingly. +4) A böngésző minden másodpercben meghívja a `tick()` metódust. Ezen belül, a `Clock` komponens beütemez egy kezelői felület frissítést a `setState()` meghívásával egy objektummal, ami a jelenlegi időt tartalmazza. A `setState()` hívásnak köszönhetően a React tudja, hogy az állapot megváltozott, és újra meghívja a `render()` metódust, hogy megtudja, minek kéne megjelennie a képernyőn. Ezúttal a `this.state.date` a `render()` metódusban más lesz, és ezért a render kimenete tartalmazni fogja a frissítet időt. A React ennek megfelelően frissíti a DOM-ot. -5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle method so the timer is stopped. +5) Ha a `Clock` komponens el lesz távolítva a DOM-ból, a React meghívja a `componentWillUnmount()` életciklus metódust és az időzítő így megáll. -## Using State Correctly {#using-state-correctly} +## Az állapot helyes használata {#using-state-Helyesly} -There are three things you should know about `setState()`. +Három dolog van, amit tudnod kell a `setState()` metódusról. -### Do Not Modify State Directly {#do-not-modify-state-directly} +### Ne módosítsd az állapotot közvetlenül {#do-not-modify-state-directly} -For example, this will not re-render a component: +Például ez nem fogja újrarenderelni a komponenst: ```js -// Wrong -this.state.comment = 'Hello'; +// Helytelen +this.state.comment = 'Helló'; ``` -Instead, use `setState()`: +Használd helyette a `setState()`-t: ```js -// Correct -this.setState({comment: 'Hello'}); +// Helyes +this.setState({comment: 'Helló'}); ``` -The only place where you can assign `this.state` is the constructor. +Az egyetlen hely, ahol bármit is hozzárendelhetsz a `this.state`-hez, az a konstruktor. -### State Updates May Be Asynchronous {#state-updates-may-be-asynchronous} +### Az állapot frissítések lehetnek aszinkronok {#state-updates-may-be-asynchronous} -React may batch multiple `setState()` calls into a single update for performance. +A React összefoghat egy csomó `setState()` hívást egy szimpla frissítésbe a teljesítmény növelése érdekében. -Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state. +Mivel a `this.props` és a `this.state` frissülhet aszinkron módon, nem szabad az értékeikre hagyatkoznod a következő állapot kiszámításához. -For example, this code may fail to update the counter: +Például ez a kód lehet, hogy nem fogja tudni frissíteni a számlálót: ```js -// Wrong +// Helytelen this.setState({ counter: this.state.counter + this.props.increment, }); ``` -To fix it, use a second form of `setState()` that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument: +Hogy ezt kijavítsd, használd a `setState()` másik formáját, ami egy függvényt fogad argumentumként egy objektum helyett. A függvény fogadja az előző állapotot első argumentumként, valamint az előző props-ot másodikként: ```js -// Correct +// Helyes this.setState((state, props) => ({ counter: state.counter + props.increment })); ``` -We used an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) above, but it also works with regular functions: +A fentiekben egy [nyíl függvényt](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) használtunk, de ez működne egy átlagos függvénnyel is: ```js -// Correct +// Helyes this.setState(function(state, props) { return { counter: state.counter + props.increment @@ -373,11 +373,11 @@ this.setState(function(state, props) { }); ``` -### State Updates are Merged {#state-updates-are-merged} +### Az állapot frissítések egyesítve vannak {#state-updates-are-merged} -When you call `setState()`, React merges the object you provide into the current state. +Amikor meghívod a `setState()` metódust, a React egyesíti az általad szolgáltatott objektumot a jelenlegi állapottal. -For example, your state may contain several independent variables: +Például az állapotod tartalmazhat számos független változót: ```js{4,5} constructor(props) { @@ -389,7 +389,7 @@ For example, your state may contain several independent variables: } ``` -Then you can update them independently with separate `setState()` calls: +Ezek aztán függetlenül frissíthetőek különálló `setState()` hívásokkal: ```js{4,10} componentDidMount() { @@ -407,41 +407,41 @@ Then you can update them independently with separate `setState()` calls: } ``` -The merging is shallow, so `this.setState({comments})` leaves `this.state.posts` intact, but completely replaces `this.state.comments`. +Az egyesítés sekély, tehát a `this.setState({comments})` érintetlenül hagyja a `this.state.posts`-ot, de teljesen lecseréli a `this.state.comments`-et. -## The Data Flows Down {#the-data-flows-down} +## Az adat lefelé folyik {#the-data-flows-down} -Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn't care whether it is defined as a function or a class. +Sem a felnőtt, sem a gyermek komponens nem tudhatja, hogy egy bizonyos komponens állapotteljes vagy állapot nélküli, és az sem kell hogy érdekelje őket, hogy függvényként vagy osztályként van-e definiálva. -This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. +Ezért van az, hogy az állapotot gyakran hívjuk helyinek, vagy egységbe zártnak. Nem hozzáférhető semelyik másik komponensből, csak abból amelyik birtokolja és beállítja. -A component may choose to pass its state down as props to its child components: +Egy komponens dönthet úgy, hogy leküldi a saját állapotát prop-ként a gyermek komponenseinek: ```js -

It is {this.state.date.toLocaleTimeString()}.

+

Az idő {this.state.date.toLocaleTimeString()}.

``` -This also works for user-defined components: +Ez működik felhasználó által definiált komponensnél is: ```js ``` -The `FormattedDate` component would receive the `date` in its props and wouldn't know whether it came from the `Clock`'s state, from the `Clock`'s props, or was typed by hand: +A `FormattedDate` komponens megkapja a `date`-et a props-ban, és nem tudja, hogy az a `Clock` állapotából, a `Clock` prop-jából jött, vagy kézzel lett beírva: ```js function FormattedDate(props) { - return

It is {props.date.toLocaleTimeString()}.

; + return

Az idő {props.date.toLocaleTimeString()}.

; } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010) -This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree. +Ezt közismerten "felülről lefelé irányuló", vagy egyirányú adatfolyamnak hívjuk. Egy adott állapotot mindig csak egy bizonyos komponens birtokolhat, és ez az állapot csakis a komponensfában 'alatta lévő' komponensek adataira vagy megjelenésére hathat. -If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down. +Ha úgy képzelsz el egy komponensfát, mint a prop-ok vízesését, minden komponens állapota olyan, mint egy plusz vízforrás, ami tetszőleges pontokon belecsatlakozik a lefelé haladó áramlatba. -To show that all components are truly isolated, we can create an `App` component that renders three ``s: +Hogy megmutassuk azt, hogy minden komponens tényleg teljesen izolált, készíthetünk egy `App` komponenst, ami három ``-t renderel: ```js{4-6} function App() { @@ -460,8 +460,8 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) +[**Próbáld ki a CodePen-en**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) -Each `Clock` sets up its own timer and updates independently. +Minden `Clock` beállítja a saját időzítőjét és ezek egymástól függetlenül frissülnek. -In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa. +Az, hogy egy React komponens állapotteljes vagy állapot nélküli, a saját implementációs részletének tekinthető, ami idővel változhat. Emiatt használhatsz állapot nélküli komponenseket állapotteljes komponenseken belül, és ugyanígy fordítva is.