diff --git a/content/docs/state-and-lifecycle.md b/content/docs/state-and-lifecycle.md index 3967ae7c9..5778712ab 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 dan Lifecycle 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). +Halaman ini akan mengenalkan tentang konsep dari _state_ dan _lifecycle_ di sebuah komponen React. Anda bisa menemukan [referensi detail _API_ komponen disini](/docs/react-component.html). -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: +Pertimbangkan contoh detak jam dari [salah satu bagian sebelumnya](/docs/rendering-elements.html#updating-the-rendered-element). Di [_Rendering Element_](/docs/rendering-elements.html#rendering-an-element-into-the-dom), kita baru saja mempelajari satu cara untuk memperbarui _UI_. Kita memanggil `ReactDOM.render()` untuk mengubah hasil _render_: ```js{8-11} function tick() { const element = (
-

Hello, world!

-

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

+

Halo, dunia!

+

Ini {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) +[**Coba di CodePen**](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. +Di bagian ini, Kita akan belajar cara membuat komponen `Clock` benar-benar dapat digunakan kembali dan terenkapsulasi. Ini akan mengatur _timer_-nya sendiri dan memperbaruinya setiap detik. -We can start by encapsulating how the clock looks: +Kita dapat memulai dengan mengenkapsulasi bagaimana jam terlihat: ```js{3-6,12} function Clock(props) { return (
-

Hello, world!

-

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

+

Halo, dunia!

+

Ini {props.date.toLocaleTimeString()}.

); } @@ -55,11 +55,11 @@ function tick() { setInterval(tick, 1000); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/dpdoYR?editors=0010) +[**Coba di CodePen**](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`. +Namun, ia melewatkan persyaratan penting: faktanya bahwa `Clock` mengatur _timer_ dan memperbarui _UI_ setiap detik harus merupakan detail implementasi dari `Clock`. -Ideally we want to write this once and have the `Clock` update itself: +Idealnya kita butuh untuk menulis ini sekali dan `Clock` dapat memperbarui dirinya sendiri: ```js{2} ReactDOM.render( @@ -68,63 +68,63 @@ ReactDOM.render( ); ``` -To implement this, we need to add "state" to the `Clock` component. +Untuk mengimplementasikan ini, kita perlu untuk menambahkan _"state"_ ke komponen `Clock`. -State is similar to props, but it is private and fully controlled by the component. +_State_ mirip dengan _props_, tetapi bersifat pribadi dan sepenuhnya dikendalikan oleh komponen. -## Converting a Function to a Class {#converting-a-function-to-a-class} +## Mengubah Sebuah Fungsi ke Sebuah Kelas {#converting-a-function-to-a-class} -You can convert a function component like `Clock` to a class in five steps: +Anda bisa mengubah sebuah _function component_ seperti `Clock` ke sebuah kelas dalam lima langkah: -1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), with the same name, that extends `React.Component`. +1. Buat sebuah [kelas ES6](https://developer.mozilla.org/id/docs/Web/JavaScript/Reference/Classes), dengan nama yang sama, yang diturunkan dari `React.Component`. -2. Add a single empty method to it called `render()`. +2. Tambah sebuah _method_ kosong yang bernama `render()`. -3. Move the body of the function into the `render()` method. +3. Pindahkan isi fungsi ke dalam _method_ `render()`. -4. Replace `props` with `this.props` in the `render()` body. +4. Ganti `props` dengan `this.props` di dalam `render()`. -5. Delete the remaining empty function declaration. +5. Hapus deklarasi fungsi kosong yang tersisa. ```js class Clock extends React.Component { render() { return (
-

Hello, world!

-

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

+

Halo, dunia!

+

Ini {this.props.date.toLocaleTimeString()}.

); } } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) +[**Coba di CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) -`Clock` is now defined as a class rather than a function. +`Clock` sekarang terdefinisikan sebagai sebuah kelas daripada fungsi -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. +_method_ `render` akan dipanggil setiap waktu ketika pembaruan terjadi, tapi selama kita me-_render_ `` simpul _DOM_ yang sama, hanya satu instansi dari kelas `Clock` yang akan digunakan. Ini memungkinkan kita untuk mengunakan fitur tambahan seperti _local state_ dan _lifecycle method_. -## Adding Local State to a Class {#adding-local-state-to-a-class} +## Menambahkan _State_ lokal ke sebuah kelas {#adding-local-state-to-a-class} -We will move the `date` from props to state in three steps: +Kita akan memindahkan `date` dari _props_ ke _state_ dalam tiga langkah: -1) Replace `this.props.date` with `this.state.date` in the `render()` method: +1) Ubah `this.props.date`_ dengan `this.state.date` di _method_ `render()`: ```js{6} class Clock extends React.Component { render() { return (
-

Hello, world!

-

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

+

Halo, dunia!

+

Ini {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`: +1) Tambah sebuah [konstruktor kelas](https://developer.mozilla.org/id/docs/Web/JavaScript/Reference/Classes#Konstruktor) yang menetapkan nilai awal `this.state`: ```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()}.

+

Halo, dunia!

+

Ini {this.state.date.toLocaleTimeString()}.

); } } ``` -Note how we pass `props` to the base constructor: +Perhatikan bagaimana kami meneruskan `props` ke konstruktor dasar: ```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`. +Kelas komponen harus selalu memanggil ke konstruktor dasar dengan `props`. -3) Remove the `date` prop from the `` element: +1) Hapus properti `date` dari elemen ``: ```js{2} ReactDOM.render( @@ -164,9 +164,9 @@ ReactDOM.render( ); ``` -We will later add the timer code back to the component itself. +Kita nanti akan menambahkan kode _timer_ kembali ke komponen itu sendiri. -The result looks like this: +Hasilnya akan terlihat seperti ini: ```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()}.

+

Halo, dunia!

+

Ini {this.state.date.toLocaleTimeString()}.

); } @@ -191,19 +191,19 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010) +[**Coba di CodePen**](https://codepen.io/gaearon/pen/KgQpJd?editors=0010) -Next, we'll make the `Clock` set up its own timer and update itself every second. +Selanjutnya, kami akan membuat `Clock` mengatur _timer_ sendiri dan memperbarui dirinya sendiri setiap detik. -## Adding Lifecycle Methods to a Class {#adding-lifecycle-methods-to-a-class} +## Menambah _Method Lifecycle_ ke Kelas {#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. +Dalam aplikasi dengan banyak komponen, sangat penting untuk membebaskan sumber daya yang diambil oleh komponen ketika mereka dihancurkan. -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. +Kami ingin [mengatur _timer_](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) setiap kali `Clock` di-_render_ di DOM untuk pertama kalinya . Ini disebut _"mounting"_ di React. -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. +Kita juga ingin untuk [menghapus timer tersebut](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) setiap kali DOM yang diproduksi oleh `Clock` dihapus. Ini disebut _"unmounting"_ di React. -We can declare special methods on the component class to run some code when a component mounts and unmounts: +Kita dapat mendeklarasi _method_ spesial di kelas komponen untuk menjalankan beberapa kode ketika sebuah komponen _mounts_ dan _unmounts_: ```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()}.

+

Halo, dunia!

+

Ini {this.state.date.toLocaleTimeString()}.

); } } ``` -These methods are called "lifecycle methods". +_Method_ ini disebut "_lifecycle method_". -The `componentDidMount()` method runs after the component output has been rendered to the DOM. This is a good place to set up a timer: +_Method_ `componentDidMount()` berjalan setelah hasil komponen sudah ter-_render_ di DOM. Ini adalah tempat yang bagus untuk mengatur _timer_: ```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`. +Perhatikan bagaimana kami menyimpan _ID_ pengatur _timer_ langsung di `this`. -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). +Ketika `this.props` diatur oleh React sendiri dan `this.state` punya arti spesial, Anda dapat dengan bebas untuk menambah _field_ tambahan di kelas secara manual jika Anda butuh untuk menyimpan sesuatu yang tidak ikut berpartisipasi di alur data (seperti _ID timer_). -We will tear down the timer in the `componentWillUnmount()` lifecycle method: +Kita akan menghapus _timer_ di _method lifecycle_ `componentWillUnmount()`: ```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. +Akhirnya, kita akan mengimplementasi sebuah _method_ bernama `tick()` yang dijalankan oleh komponen `Clock` setiap detik. -It will use `this.setState()` to schedule updates to the component local state: +Itu akan mengunakan `this.setState()` untuk menjadwal pembaruan ke _state_ lokal milik komponen: ```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()}.

+

Hello, dunia!

+

Ini {this.state.date.toLocaleTimeString()}.

); } @@ -300,72 +300,72 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) +[**Coba di CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) -Now the clock ticks every second. +Sekarang jam akan berdetak setiap waktu. -Let's quickly recap what's going on and the order in which the methods are called: +Mari kita rekap dengan cepat apa yang terjadi dan urutan _method_ yang dipanggil: -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) Ketika `` diberikan ke `ReactDOM.render()`, React memanggil konstruktor dari komponen `Clock`. Ketika `Clock` perlu untuk menampilkan waktu saat ini, dia menginisialisai `this.state` dengan sebuah obyek termasuk waktu saat ini. Kita nantinya akan memperbarui status ini. -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) React kemudian memanggil _method_ `render()` milik komponen `Clock`. Beginilah cara React belajar apa yang harusnya ditampilkan di layar. React kemudian memperbarui _DOM_ untuk mencocokan hasil _render_ `Clock`. -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) Ketika hasil `Clock` dimasukkan ke dalam _DOM_, React memanggil _method lifecycle_ `componentDidMount()`. Didalamnya, komponen `Clock` menyuruh _browser_ untuk mengatur sebuah _timer_ untuk memanggil _method_ `tick()` milik komponen sekali per detik. -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) Setiap detik _browser_ memanggil _method_ `tick()`. Didalamnya, komponen `Clock` menjadwal pembaruan _UI_ dengan memanggil `setState()` dengan sebuah obyek berisi waktu sekarang. Berkat panggilan `setState()`, React mengetahui _state_ sudah berubah, dan memanggil _method_ `render()` lagi untuk mempelajari apa yang harusnya ada di layar. Kali ini, `this.state.date` di `render()` _method_ akan berbeda, dan jadi hasil _render_ akan mencakup waktu yang diperbarui. React telah memperbarui _DOM_ dengan sesuai. -5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle method so the timer is stopped. +5) Jika komponen `Clock` dihapus dari _DOM_, React memanggil _method lifecycle_ `componentWillUnmount()` jadi _timer_ akan berhenti. -## Using State Correctly {#using-state-correctly} +## Menggunakan _State_ Dengan Benar {#using-state-correctly} -There are three things you should know about `setState()`. +Ada tiga hal yang harus Anda ketahui tentang `setState()`. -### Do Not Modify State Directly {#do-not-modify-state-directly} +### Jangan mengubah _State_ Secara Langsung {#do-not-modify-state-directly} -For example, this will not re-render a component: +Sebagai contoh, ini tidak akan me-_render_ komponen : ```js -// Wrong -this.state.comment = 'Hello'; +// Salah +this.state.comment = 'Halo'; ``` -Instead, use `setState()`: +Sebagai gantinya, gunakan `setState()`: ```js -// Correct -this.setState({comment: 'Hello'}); +// Benar +this.setState({comment: 'Halo'}); ``` -The only place where you can assign `this.state` is the constructor. +Satu-satunya tempat di mana Anda dapat menetapkan `this.state` adalah di konstruktor. -### State Updates May Be Asynchronous {#state-updates-may-be-asynchronous} +### Pembaruan _State_ Mungkin _Asynchronous_ {#state-updates-may-be-asynchronous} -React may batch multiple `setState()` calls into a single update for performance. +React dapat mengelompokkan beberapa panggilan `setState()` menjadi satu untuk kinerja lebih baik. -Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state. +Karena `this.props` dan `this.state` mungkin diperbarui secara _asynchronous_, Anda seharusnya tidak mengandalkan nilai-nilai tersebut untuk menghitung _State_ berikutnya. -For example, this code may fail to update the counter: +Sebagai contoh, kode ini mungkin gagal untuk memperbarui penghitung: ```js -// Wrong +// Salah 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: +Untuk memperbaikinya, pakai bentuk kedua dari `setState()` yang menerima fungsi daripada sebuah objek. Fungsi itu akan menerima _state_ sebelumnya sebagai argumen pertama, dan _props_ pada waktu itu pembaruanya di terapkan ke argumen kedua: ```js // Correct 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: +Kita menggunakan [_arrow function_](https://developer.mozilla.org/id/docs/Web/JavaScript/Reference/Functions/Arrow_functions) diatas, tetapi juga bisa menggunakan fungsi biasa: ```js -// Correct +// Benar 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} +### Pembaruan _State_ Digabungkan {#state-updates-are-merged} -When you call `setState()`, React merges the object you provide into the current state. +Ketika Anda memanggil `setState()`, React mengabungkan obyek yang anda siapkan ke _state_ saat ini. -For example, your state may contain several independent variables: +Sebagai contoh, _state_ anda mungkin menganduk beberapa variabel independen: ```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: +Kemudian Anda dapat memperbarui mereka secara terpisah dengan memanggil `setState()` yang terpisah: ```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`. +Pengabunganya dangkal, jadi `this.setState({comments})` meninggalkan `this.state.posts` dengan utuh, tetapi sepenuhnya menggantikan `this.state.comments`. -## The Data Flows Down {#the-data-flows-down} +## Data Mengalir ke Bawah {#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. +Baik komponen induk maupun anak tidak tahu apakah komponen tertentu mengandung _state_ atau tidak, dan mereka tidak seharusnya peduli apakah itu didefinisikan sebagai fungsi atau kelas. -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. +Inilah sebabnya mengapa _state_ kadang disebut lokal atau terenkapsulasi. Itu tidak dapat diakses oleh komponen apa pun selain dari yang memiliki dan menetapkannya. -A component may choose to pass its state down as props to its child components: +Sebuah komponen dapat memilih untuk menurunkan _state_ sebagai _props_ ke komponen turunannya: ```js -

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

+

Ini {this.state.date.toLocaleTimeString()}.

``` -This also works for user-defined components: +Ini juga berfungsi untuk komponen yang ditentukan pengguna: ```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: +Komponen `FormattedDate` akan menerima `date` _props_-nya dan tidak akan tahu apakah itu datang dari _state_ milik `Clock`, dari _props_ milik `Clock`, atau itu diketik dengan tangan: ```js function FormattedDate(props) { - return

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

; + return

Ini {props.date.toLocaleTimeString()}.

; } ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRqNB?editors=0010) +[**Coba di CodePen**](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. +Ini umumnya memanggil aliran data "atas-bawah" atau "searah". Semua _state_ selalu dimiliki oleh komponen spesifik, dan semua data atau _UI_ yang berasal dari _state_ tersebut hanya bisa mempengaruhi pohon komponen "di bawah" mereka. -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. +Jika Anda membanyangkan pohon komponen sebagai air terjun dari _props_, tiap _state_ milik komponen seperti sebuah sumber air yang bergabung dengannya pada titik acak tetapi juga mengalir ke bawah. -To show that all components are truly isolated, we can create an `App` component that renders three ``s: +Untuk menunjukkan jika semua komponen benar-benar terisolasi, Kita dapat membuat sebuah komponen `App` yang me-_render_ tiga ``: ```js{4-6} function App() { @@ -460,8 +460,8 @@ ReactDOM.render( ); ``` -[**Try it on CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) +[**Coba di CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) -Each `Clock` sets up its own timer and updates independently. +Setiap `Clock` membuat _timer_-nya sendiri dan memperbaruinya secara independen. -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. +Di aplikasi React, apakah suatu komponen memiliki _state_ atau tidak itu dianggap sebagai detail implementasi komponen yang dapat berubah dari waktu ke waktu. Anda dapat menggunakan komponen tanpa _state_ di dalam komponen dengan _state_, dan sebaliknya.