diff --git a/content/docs/state-and-lifecycle.md b/content/docs/state-and-lifecycle.md index cbd8f684a..ea189ec4d 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: State ve Yaşam Döngüsü permalink: docs/state-and-lifecycle.html redirect_from: - "docs/interactivity-and-dynamic-uis.html" @@ -8,9 +8,9 @@ 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). +Bu sayfada, state kavramı ve React bileşlerinin yaşam döngüsü tanıtılacaktır. Bileşen API'si hakkında ayrıntılı bilgi için, [bu dokümana](/docs/react-component.html) bakabilirsiniz. -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: +[Önceki bölümlerde bahsettiğimiz](/docs/rendering-elements.html#updating-the-rendered-element), analog saat örneğini ele alacağız. Hatırlayacağınız gibi, [elemetlerin Render Edilmesi](/docs/rendering-elements.html#rendering-an-element-into-the-dom) bölümünde, kullanıcı arayüzünün yalnızca tek yönlü güncellenmesine yer vermiştik. Bunu `ReactDOM.render()` metodu ile geçekleştirebiliyorduk: ```js{8-11} function tick() { @@ -29,11 +29,11 @@ function tick() { setInterval(tick, 1000); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/gwoJZk?editors=0010) +[**CodePen'de deneyin**](http://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. +Bu bölümde ise, `Clock` bileşenini nasıl sarmalayacağımıza ve tekrar kullanılabilir hale getireceğimize değineceğiz. Bu bileşen, kendi zamanlayıcısını başlatacak ve her saniye kendisini güncelleyecek. -We can start by encapsulating how the clock looks: +Öncelikle Clock'u, ayrı bir bileşen halinde sarmalayarak görüntüleyelim: ```js{3-6,12} function Clock(props) { @@ -55,11 +55,11 @@ function tick() { setInterval(tick, 1000); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010) +[**CodePen'de deneyin**](http://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`. +Güzel görünüyor ancak bu aşamada kritik bir gereksinimi atladık: `Clock`'un kendi zamanlayıcısını ayarlaması, ve her saniye kullanıcı arayüzünü güncellemesi işini kendi bünyesinde gerçekleştirmesi gerekiyordu. -Ideally we want to write this once and have the `Clock` update itself: +Aşağıdaki kodu bir kere yazdığımızda, `Clock`'un artık kendi kendisini güncellemesini istiyoruz: ```js{2} ReactDOM.render( @@ -68,25 +68,25 @@ ReactDOM.render( ); ``` -To implement this, we need to add "state" to the `Clock` component. +Bunu yapmak için, `Clock` bileşenine **state** eklememiz gerekiyor. -State is similar to props, but it is private and fully controlled by the component. +State'ler, prop'larla benzerlik gösterir. Fakat sadece ilgili bileşene özeldir ve yalnızca o bileşen tarafından kontrol edilirler. -We [mentioned before](/docs/components-and-props.html#functional-and-class-components) that components defined as classes have some additional features. Local state is exactly that: a feature available only to classes. +Sınıf olarak oluşturulan bişeşenlerin, fonksiyon bileşenlerine göre bazı ek özelliklerinin bulunduğundan [bahsetmiştik](/docs/components-and-props.html#functional-and-class-components). Bahsettiğimiz ek özellik yerel state değişkenidir ve sadece sınıf bileşenlerine özgüdür. -## Converting a Function to a Class {#converting-a-function-to-a-class} +## Bir Fonksiyonun Sınıfa Dönüştürülmesi {#converting-a-function-to-a-class} -You can convert a function component like `Clock` to a class in five steps: +`Clock` gibi bir fonksiyon bileşenini 5 adımda sınıf bileşenine dönüştürebilirsiniz: -1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), with the same name, that extends `React.Component`. +1. Öncelikle, fonksiyon ismiyle aynı isimde bir [ES6 sınıfı](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) oluşturun. Ve bu sınıfı `React.Component`'tan türetin. -2. Add a single empty method to it called `render()`. +2. Sınıfın içerisine, `render()` adında boş bir fonksiyon ekleyin. -3. Move the body of the function into the `render()` method. +3. Fonksiyon bileşeni içerisindeki kodları `render()` metoduna taşıyın. -4. Replace `props` with `this.props` in the `render()` body. +4. `render()` metodu içerisindeki `props` yazan yerleri, `this.props` ile değiştirin. -5. Delete the remaining empty function declaration. +5. Son olarak, içi boşaltılmış fonksiyonu tamamen silin. ```js class Clock extends React.Component { @@ -101,17 +101,17 @@ class Clock extends React.Component { } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) +[**CodePen'de deneyin**](http://codepen.io/gaearon/pen/zKRGpo?editors=0010) -`Clock` is now defined as a class rather than a function. +Önceden fonksiyon bileşeni olan `Clock`, artık bir sınıf bileşeni haline gelmiş oldu. -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. +Bu kodda `render` metodumuz, her güncelleme olduğunda yeniden çağrılacaktır. Fakat `` bileşenini aynı DOM düğümünde render ettiğimizden dolayı, `Clock` sınıfının yalnızca bir örneği kullanılacaktır. -## Adding Local State to a Class {#adding-local-state-to-a-class} +## Bir Sınıfa Yerel State'in Eklenmesi {#adding-local-state-to-a-class} -We will move the `date` from props to state in three steps: +`date` değişkenini, props'tan state'e taşımamız gerekiyor. Bunu 3 adımda gerçekleştirebiliriz: -1) Replace `this.props.date` with `this.state.date` in the `render()` method: +1) `render()` metodundaki `this.props.date`'i `this.state.date` ile değiştirelim: ```js{6} class Clock extends React.Component { @@ -126,7 +126,7 @@ class Clock extends React.Component { } ``` -2) Add a [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor) that assigns the initial `this.state`: +2) `state`'in ilk kez oluşturulacağı yer olan [sınıf constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor)'ını ekleyelim: ```js{4} class Clock extends React.Component { @@ -146,7 +146,7 @@ class Clock extends React.Component { } ``` -Note how we pass `props` to the base constructor: +`props`'ı, constructor içerisinde nasıl oluşturduğumuza yakından bakalım: ```js{2} constructor(props) { @@ -155,9 +155,9 @@ Note how we pass `props` to the base constructor: } ``` -Class components should always call the base constructor with `props`. +Sınıf bileşenleri `React.Component` sınıfından türetildikleri için, daima `super(props)`'u çağırmaları gerekir. -3) Remove the `date` prop from the `` element: +3) `` elementinden `date` prop'unu çıkaralım: ```js{2} ReactDOM.render( @@ -166,9 +166,7 @@ ReactDOM.render( ); ``` -We will later add the timer code back to the component itself. - -The result looks like this: +Zamanlayıcı kodunu, daha sonra `Clock` bileşenin içerisine ekleyeceğiz. Fakat şimdilik `Clock` bileşeninin son hali aşağıdaki gibi olacaktır: ```js{2-5,11,18} class Clock extends React.Component { @@ -193,19 +191,19 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010) +[**CodePen'de deneyin**](http://codepen.io/gaearon/pen/KgQpJd?editors=0010) -Next, we'll make the `Clock` set up its own timer and update itself every second. +Şimdi `Clock` bileşenini, kendi zamanlayıcısını kuracak ve her saniye kendisini güncelleyecek şekilde ayarlayalım. -## Adding Lifecycle Methods to a Class {#adding-lifecycle-methods-to-a-class} +## Bir Sınıfın Yaşam Döngüsü Kodlarının Eklenmesi {#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. +Birçok bileşene sahip uygulamalarda, bileşenler yok edildiğinde ilgili kaynakların bırakılması çok önemlidir. -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. +`Clock` bileşeni ilk kez DOM'a render edildiğinde bir [zamanlayıcı](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) kurmak istiyoruz. React'te bu olaya "mounting" (değişkenin takılması) adı verilir. -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. +Ayrıca, `Clock` bileşeni DOM'dan çıkarıldığında, zamanlayıcının da [temizlenmesini](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) istiyoruz. React'te bu olaya "unmounting" (değişkenin çıkarılması) adı verilir. -We can declare special methods on the component class to run some code when a component mounts and unmounts: +`Clock` bileşeni takılıp çıkarıldığında bazı işleri gerçekleştirebilmek için özel metodlar tanımlayabiliriz: ```js{7-9,11-13} class Clock extends React.Component { @@ -233,9 +231,9 @@ class Clock extends React.Component { } ``` -These methods are called "lifecycle methods". +Bu metodlara "lifecycle methods" (yaşam döngüsü metodları) adı verilir. -The `componentDidMount()` method runs after the component output has been rendered to the DOM. This is a good place to set up a timer: +Bileşenin çıktısı, DOM'a render edildikten sonra `componentDidMount()` metodu çalıştırılır. Burası aynı zamanda bir zamanlayıcı oluşturmak için en elverişli yerdir: ```js{2-5} componentDidMount() { @@ -246,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`'e zamanlayıcı ID'sini nasıl atadığımızı inceleyebilirsiniz. -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). +Daha önce de belirttiğimiz gibi, `this.props` React tarafından yönetiliyor, ve `this.state`'in de özel bir yaşam döngüsü var. Eğer `timerID` gibi veri akışına dahil olmayan değişkenleri saklamanız gerekiyorsa, bu örnekte yaptığımız gibi sınıf içerisinde değişkenler tanımlayabilirsiniz. -We will tear down the timer in the `componentWillUnmount()` lifecycle method: +Oluşturduğumuz zamanlayıcıyı `componentWillUnmount()` yaşam döngüsü metodu içerisinde `Clock` bileşeninden söküp çıkaralım: ```js{2} componentWillUnmount() { @@ -258,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. +Son olarak, `Clock` bileşeninin saniyede bir çalıştıracağı `tick()` fonksiyonunu kodlayalım. -It will use `this.setState()` to schedule updates to the component local state: +`tick()` fonksiyonu, `this.setState()`'i çağırarak `Clock` bileşeninin yerel state'ini güncelleyecektir: ```js{18-22} class Clock extends React.Component { @@ -302,72 +300,72 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) +[**CodePen'de deneyin**](http://codepen.io/gaearon/pen/amqdNA?editors=0010) -Now the clock ticks every second. +Artık saat, her saniye başı tikleyerek mevcut zamanı görüntüleyecektir. -Let's quickly recap what's going on and the order in which the methods are called: +Şimdi kısa bir özet geçerek neler yaptığımızı ve sırasıyla hangi metotların çağrıldığını kontrol edelim: -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) `ReactDOM.render()` metoduna `` aktarıldığı zaman React, `Clock` bileşeninin constructor'ını çağırır. `Clock` bileşeni, mevcut saati görüntülemesi gerektiğinden dolayı, `this.state`'e o anki zamanı atar. Daha sonra bu state güncellenecektir. -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) Devamında React, `Clock` bileşeninin `render()` metodunu çağırır. Bu sayede React, ekranda nelerin gösterilmesi gerektiğini bilir. Sonrasında ise `Clock`'un render edilmiş çıktısı ile eşleşmek için ilgili DOM güncellemelerini gerçekleştirir. -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) `Clock` bileşeninin çıktısı DOM'a eklendiğinde, yaşam döngüsündeki `componentDidMount()` metodu çağrılır. Bu metodda `Clock` bileşeni, her saniyede bir `tick()` metodunun çalıştırılması gerektiğini tarayıcıya bildirir. -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) Tarayıcı her saniyede bir `tick()` metodunu çağırır. `tick()` metodunda `Clock` bileşeni, kullanıcı arayüzünü güncellemek için `setState()` metodunu çağırır ve bu metoda mevcut tarih/saat değerini aktarır. `setState()`'in çağrılması sayesinde React, state'in değiştiğini anlar ve ekranda neyin görüntüleneceğini anlamak için tekrar `render()` metodunu çağırır. Artık `render()` metodundaki `this.state.date`'in değeri eski halinden farklı olduğundan dolayı, render çıktısı güncellenmiş zamanı içerecek demektir. Buna göre React, DOM'u ilgili şekilde günceller. -5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle method so the timer is stopped. +5) Eğer `Clock` bileşeni, DOM'dan çıkarılırsa, yaşam döngüsündeki `componentWillUnmount()` metodu çağrılır ve tarayıcı tarafından zamanlayıcı durdurulmuş olur. -## Using State Correctly {#using-state-correctly} +## State'in Doğru Kullanımı {#using-state-correctly} -There are three things you should know about `setState()`. +`setState()` hakkında bilmeniz gereken 3 şey bulunmaktadır. -### Do Not Modify State Directly {#do-not-modify-state-directly} +### State'i Direkt Olarak Değiştirmeyiniz {#do-not-modify-state-directly} -For example, this will not re-render a component: +Aşağıdaki kod, bileşenin yeniden render edilmesini **gerçekleştirmez**: ```js -// Wrong +// Yanlış kullanım this.state.comment = 'Hello'; ``` -Instead, use `setState()`: +Bunun yerine `setState()` kullanınız: ```js -// Correct +// Doğru kullanım this.setState({comment: 'Hello'}); ``` -The only place where you can assign `this.state` is the constructor. +`this.state`'e atama yapmanız gereken tek yer, ilgili bileşenin constructor'ıdır. -### State Updates May Be Asynchronous {#state-updates-may-be-asynchronous} +### State Güncellemeleri Asenkron Olabilir {#state-updates-may-be-asynchronous} -React may batch multiple `setState()` calls into a single update for performance. +React, çoklu `setState()` çağrılarını, performans için tekil bir güncellemeye dönüştürebilir. -Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state. +`this.props` ve `this.state`, asenkron olarak güncellenebildiklerinden dolayı, sonraki state'i hesaplarken bu nesnelerin mevcut değerlerine **güvenmemelisiniz**. -For example, this code may fail to update the counter: +Örneğin, aşağıdaki kod `counter`'ı güncellemeyebilir: ```js -// Wrong +// Yanlış kullanım 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: +Bunu düzeltmek için, `setState()`'in ikinci formunu kullanmamız gerekir. Bu formda `setState()` fonksiyonu, parametre olarak nesne yerine fonksiyon alır. Bu fonksiyon, ilk parametre olarak önceki state'i, ikinci parametre olarak da o anda güncellenen props değerini alır: ```js -// Correct +// Doğru kullanım 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: +Yukarıda bir [ok fonksiyonu](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) kullandık. Fakat normal fonksiyonlarla da gayet çalışabilir: ```js -// Correct +// Doğru kullanım this.setState(function(state, props) { return { counter: state.counter + props.increment @@ -375,11 +373,11 @@ this.setState(function(state, props) { }); ``` -### State Updates are Merged {#state-updates-are-merged} +### State Güncellemeleri Birleştirilir {#state-updates-are-merged} -When you call `setState()`, React merges the object you provide into the current state. +React, `setState()`'i çağırdığınızda, parametre olarak verdiğiniz nesneyi alıp mevcut state'e aktarır. -For example, your state may contain several independent variables: +Örneğin, state'iniz aşağıdaki gibi birçok bağımsız değişkeni içerebilir: ```js{4,5} constructor(props) { @@ -391,7 +389,7 @@ For example, your state may contain several independent variables: } ``` -Then you can update them independently with separate `setState()` calls: +Ve siz de bu değişkenleri, ayrı birer `setState()` çağrıları ile güncellemek isteyebilirsiniz: ```js{4,10} componentDidMount() { @@ -409,27 +407,27 @@ 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`. +Birleşme işlemi yüzeysel olduğundan dolayı, `this.setState({comments})` çağrısı `this.state.posts` değişkenini değişmeden bırakırken, `this.state.comments`'i tamamıyla değiştirecektir. -## The Data Flows Down {#the-data-flows-down} +## Verinin Alt Bileşenlere Aktarılması {#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. +Ne üst, ne de alt bileşenler, belirli bir bileşenin state'li veya state'siz olduğunu bilemez. Ayrıca o bileşenin fonksiyon veya sınıf olarak tanımlanmasını da önemsemezler. -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. +Bu nedenle state'e, **yerel state** denir. State, kendisine sahip olan ve kendisini ayarlayan bileşen haricinde hiçbir bileşen için erişilebilir değildir. -A component may choose to pass its state down as props to its child components: +Bir bileşen kendi state'ini, prop'lar aracılığıyla alt bileşenlere aktarabilir: ```js

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

``` -This also works for user-defined components: +Kullanıcı tanımlı bileşenler için de bu durum geçerlidir: ```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: +`FormattedDate` bileşeni, `date` değişkenini props'tan alabilir. Ve bunu alırken `Clock`'un state'inden mi yoksa prop'undan mı geldiğini bilemez. Hatta `date` değişkeni, `Clock` bileşeni içerisinde state'ten harici olarak tanımlanmış bir değer de olabilir ve bunu da bilmesine imkanı yoktur: ```js function FormattedDate(props) { @@ -437,13 +435,13 @@ function FormattedDate(props) { } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010) +[**CodePen'de deneyin**](http://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. +Bu olaya genellikle **yukarıdan-aşağıya** veya **tek yönlü** veri akışı denir. Her state, belirli bir bileşen tarafından tutulur. Bu bileşenden türetilen herhangi bir veri veya kullanıcı arayüzü, yalnızca bu bileşenin altındaki bileşen ağacına etki edebilir. -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. +Bileşen ağacını, prop'lardan oluşan bir şelale olarak düşünebilirsiniz. Her bileşenin state'i, prop'ları istenilen bir noktada birleştirebilen ve aynı zamanda alt bileşenlere de akıtan ek bir su kaynağı gibidir. -To show that all components are truly isolated, we can create an `App` component that renders three ``s: +Tüm bileşenlerin tamamen izole olduğunu göstermek için, 3 adet `` render eden bir `App` bileşeni oluşturabiliriz: ```js{4-6} function App() { @@ -462,8 +460,8 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) +[**CodePen'de deneyin**](http://codepen.io/gaearon/pen/vXdGmd?editors=0010) -Each `Clock` sets up its own timer and updates independently. +Bu örnekte yer alan her bir `Clock` bileşeni, kendi zamanlayıcısını oluşturup, birbirinden bağımsız bir şekilde güncellemektedir. -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. +React uygulamalarında, bir bileşenin state'li veya state'siz olması, bir kodlama detayıdır ve zaman içerisinde değişkenlik gösterebilir. State'li bileşenler içerisinde, state'siz bileşenleri kullanabilirsiniz. Veya bu durumun tam tersi de geçerlidir.