diff --git a/content/docs/state-and-lifecycle.md b/content/docs/state-and-lifecycle.md index 3967ae7c9..06679a800 100644 --- a/content/docs/state-and-lifecycle.md +++ b/content/docs/state-and-lifecycle.md @@ -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). +Энэхүү хуудас нь React компонентийн state болон амьдралын мѳчлѳгийн ойлголтыг ѳгѳх зорилготой. [Илүү дэлгэрэнгүй мэдээллийг эндээс олох боломжтой](/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: +[Ѳмнѳ нь хийсэн цаг тоолуурыг](/docs/rendering-elements.html#updating-the-rendered-element) жишээ болгоё. [Элемент рендэрлэх](/docs/rendering-elements.html#rendering-an-element-into-the-dom) заавар дээр хэрэглэгчийн интерфэйсыг шинэчлэх нэг арга болох `ReactDOM.render()` ашиглахыг үзсэн билээ. ```js{8-11} function tick() { @@ -31,9 +31,9 @@ setInterval(tick, 1000); [**Try it on 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. +Харин энэ удаа бид `Clock` компонентийг жинхэнэ утгаар нь дахин ашиглах боломжтой цогц болгоно. Ѳѳрѳѳ цагаа тохируулж ѳѳрѳѳ секунд бүрт шинэчлэгдэнэ гэсэн үг. -We can start by encapsulating how the clock looks: +Цаг маань хэрхэн харагдахаас эхэлье ```js{3-6,12} function Clock(props) { @@ -57,9 +57,9 @@ setInterval(tick, 1000); [**Try it on 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`. +Дээрхи ѳѳрчлѳлтѳд зайлшгүй шаардлагатай зүйл болох: `Clock` ѳѳрѳѳ цагаа тааруулж хэрэглэгчийн интерфэйсыг секунд тутам шинэчлэх ёстой байдал дутмаг байна. -Ideally we want to write this once and have the `Clock` update itself: +Ерѳнхийдѳѳ бид үүнийг ганцхан удаа бичээд `Clock` ѳѳрѳѳ шинэчлэгдэх хэрэгтэй байгаа. ```js{2} ReactDOM.render( @@ -68,23 +68,23 @@ ReactDOM.render( ); ``` -To implement this, we need to add "state" to the `Clock` component. +Дээрх шиг болгохын тулд бид "state" -ыг `Clock` компонентод нэмж ѳгѳх хэрэгтэй -State is similar to props, but it is private and fully controlled by the component. +State нь пропстой адил боловч зѳвхѳн компонент нь хэмжээнд л харъяалагдаж, зѳвхѳн компонент нь л удирдах эрхтэй -## Converting a Function to a Class {#converting-a-function-to-a-class} +## Функцыг Class-руу хѳрвүүлж буй нь {#converting-a-function-to-a-class} -You can convert a function component like `Clock` to a class in five steps: +Та `Clock` шиг бүтэцтэй компонентийг дараах 5 алхамаар хѳрвүүлнэ: -1. Create an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), with the same name, that extends `React.Component`. +1. Адил нэртэй `React.Component` -ыг удамшуулсан [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) үүсгэнэ. -2. Add a single empty method to it called `render()`. +2. `render()` гэх нэртэй method зарлана. -3. Move the body of the function into the `render()` method. +3. Функцийн эх бие хэсгийг `render()` method дотор оруулна. -4. Replace `props` with `this.props` in the `render()` body. +4. `render()` доторх `props` -ыг `this.props` болгож бичнэ. -5. Delete the remaining empty function declaration. +5. Функцээс үлдсэн хэсгийг устгана. ```js class Clock extends React.Component { @@ -101,15 +101,15 @@ class Clock extends React.Component { [**Try it on CodePen**](https://codepen.io/gaearon/pen/zKRGpo?editors=0010) -`Clock` is now defined as a class rather than a function. +`Clock` одоо функц биш класс боллоо. -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. +`render` method нь шинэчлэгдэх бүрт дуудагдах ба DOM -дотор нэг л `` компонент рендэрлэж байгаа тул нэг л instance үүснэ. Ингэснээр нэмэлт боломжууд, state, болон мѳчлѳгийн method-уудыг ашиглах боломжтой болно. -## Adding Local State to a Class {#adding-local-state-to-a-class} +## Класст state оруулах нь {#adding-local-state-to-a-class} -We will move the `date` from props to state in three steps: +Пропст байгаа `date` -ыг дараах 3 алхамаар state-руу оруулна. -1) Replace `this.props.date` with `this.state.date` in the `render()` method: +1) `render()` доторх `this.props.date` -ыг `this.state.date` ээр сольж бичнэ: ```js{6} class Clock extends React.Component { @@ -124,7 +124,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) Анхны утга оноох `this.state` -ыг [class constructor](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Constructor)-ыг ашиглан нэмж ѳгнѳ: ```js{4} class Clock extends React.Component { @@ -144,7 +144,7 @@ class Clock extends React.Component { } ``` -Note how we pass `props` to the base constructor: +Конструкторт хэрхэн `props` дамжуулж байгааг анхаарна уу: ```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`. +Класс компонент үргэлж конструктор-ыг `props` той дуудах ёстой. -3) Remove the `date` prop from the `` element: +3) ``-ын элементээс `date` prop-ыг устгана: ```js{2} ReactDOM.render( @@ -164,9 +164,9 @@ ReactDOM.render( ); ``` -We will later add the timer code back to the component itself. +Бид дараа нь timer -ын кодыг оруулж ирнэ. -The result looks like this: +Үр дүн харагдах байдал: ```js{2-5,11,18} class Clock extends React.Component { @@ -193,17 +193,17 @@ ReactDOM.render( [**Try it on 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. +Дараа нь, `Clock` -ыг ѳѳрѳѳ timer-аа тохируулж ѳѳрѳѳ ѳѳрийгѳѳ секунд тутам шинэчилдэг болгоно. -## Adding Lifecycle Methods to a Class {#adding-lifecycle-methods-to-a-class} +## Класст амьдралын мѳчлѳгийн method нэмнэ {#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. +Олон компонент бүхий аппликейшнд, компонент устгагдах үед ашиглагдаж байсан нѳѳцѳѳ суллах нь маш чухал. -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` DOM-д анх рендэрлэх үед нь [цагыг тохируулах](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) шаардлагатай. Үүнийг React-д "mounting" гэж нэрлэдэг. -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. +Мѳн бид DOM дээрээс `Clock` устгагдах үед [цагыг цэвэрлэх](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) хэрэгтэй. Үүнийг React-д "unmounting" гэдэг. -We can declare special methods on the component class to run some code when a component mounts and unmounts: +Бид компонент дотор компонентийг mount, unmount хийгдэх үед зориулсан тусгай method ашиглаж ямар нэг код ажиллуулж болдог: ```js{7-9,11-13} class Clock extends React.Component { @@ -231,9 +231,9 @@ class Clock extends React.Component { } ``` -These methods are called "lifecycle methods". +Эдгээр method-уудыг "амьдралын мѳчлѳгийн" 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: +`componentDidMount()` нь компонент DOM дээр рендэр хийгдсэний дараа ажиллана. Энд цагыг тохируулах нь хамгийн тохиромжтой байх нь: ```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` -д цагын ID хадгалж байгааг сайн анзаарна уу. -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). +`this.props` -ыг React ѳѳрѳѳ хийж байгаа бол `this.state` нь арай илүү давуу талтай буюу та хүссэнээрээ ѳгѳгдѳл хадгалж болдог. Мэдээж энэ нь зѳвхѳн дотроо л зохицуулагдаж болдог бол шүү дээ, яг timerID шиг -We will tear down the timer in the `componentWillUnmount()` lifecycle method: +Бид `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. +Эцэст нь `Clock` компонент секунд тутам `tick()` функцээ дууддаг болгоно. -It will use `this.setState()` to schedule updates to the component local state: +`this.setState()` ашиглан дотоод state дээ шинэчлэлтийг хийж байна: ```js{18-22} class Clock extends React.Component { @@ -302,49 +302,50 @@ ReactDOM.render( [**Try it on CodePen**](https://codepen.io/gaearon/pen/amqdNA?editors=0010) -Now the clock ticks every second. +Ингээд цаг маань секунд тутам ажиллаж байна. -Let's quickly recap what's going on and the order in which the methods are called: +Дээр үзсэн зүйлээ дахин нэг базаад хаана нь аль method ашигласан эсэхээ үзье: -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()`-руу дамжуулах үед, React `Clock` компонентийн конструктор функцийг дуудана. `Clock` маань тухайн үеийн цагыг харуулах хэрэгтэй учир, `this.state` тухайн цагыг авч ажиллана. Дараа нь энэ state -ыг шинэчилнэ. -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 дараа нь `Clock` компонентийн `render()` дуудана. Ингэж React нь дэлгэц дээр юу харуулахаа мэддэг. Дараа нь render -ын гаралтаас хамаарч DOM -ыг шинэчилнэ. -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` -ын гаралт DOM -д орох үед, React нь хѳтѳч дээр цаг тааруулах, `tick()` функцыг секунд тутам ажиллуулахаар `componentDidMount()` амьдралын мѳчлѳг дууддаг. -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) Секунд тутам хѳтѳч `tick()` функцыг дуудна. Дотор нь `Clock` компонент `setState()` ашиглан тухайн үеийн цагийг хадгалж буй state-ыг хэрэглэгчийн интерфэйсыг шинэчлэхээр бэлддэг. `setState()` -ын ачаар React, state ѳѳрчлѳгдснийг мэдэж `render()` method -ыг дуудаж дэлгэц дээр юу харуулахаа мэддэг. Энэ удаа `render()` method доторх `this.state.date` ѳѳрчлѳгдсѳн, тиймээс рендэр хийгдсэн үр дүн шинэчлэгдсэн цагыг харуулж, React үүнээс үүдэн DOM -ыг ѳѳрчлѳнѳ. -5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle method so the timer is stopped. +5) Хэрвээ `Clock` компонент DOM дээрээс уствал, React `componentWillUnmount()` ийг дуудаж цаг зогсоно. -## Using State Correctly {#using-state-correctly} +## State-ыг зѳвѳѳр ашиглах нь {#using-state-correctly} -There are three things you should know about `setState()`. +`setState()`-ын талаар мэдэх шаардлагатай 3 зүйлс бий. -### Do Not Modify State Directly {#do-not-modify-state-directly} +### State-ыг шууд ѳѳрчилж болохгүй {#do-not-modify-state-directly} For example, this will not re-render a component: +Жишээ нь доорхи нь компонентийг дахин рендэр хийхгүй ```js // Wrong this.state.comment = 'Hello'; ``` -Instead, use `setState()`: +Оронд нь `setState()` ашигла: ```js // Correct this.setState({comment: 'Hello'}); ``` -The only place where you can assign `this.state` is the constructor. +`this.state`-ыг зааж ѳгѳх цор ганц газар нь конструктор юм. -### State Updates May Be Asynchronous {#state-updates-may-be-asynchronous} +### State шинэчлэх нь Asynchronous байж болно {#state-updates-may-be-asynchronous} -React may batch multiple `setState()` calls into a single update for performance. +React хүчин чадал хэмнэх үүднээс олон `setState()`-ыг нэг үйлдэл дотор дуудах шаардлага гардаг -Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state. +Учир нь `this.props` болон `this.state` зэрэг шинэчлэгдэх боломжтой, тэгэхээр эдгээрийн утга дээр үндэслэн дараагийн state-ыг тооцоолох нь утгагүй болж байна. -For example, this code may fail to update the counter: +Жишээ нь доорхи код тоологчийг шинэчлэхдээ алдаа гарна: ```js // Wrong @@ -353,7 +354,7 @@ this.setState({ }); ``` -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: +Үүнийг засахын тулд `setState()`-ын нэг боломж болох функцыг аргумент болгон авах боломжыг ашиглая. Функц ѳмнѳх state-ыг эхний аргумент болгож, тухайн шинэчлэгдсэн цагыг 2 дахь аргумент props болгож авна: ```js // Correct @@ -362,7 +363,7 @@ this.setState((state, props) => ({ })); ``` -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: +Бид [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) ашигласан боловч энгийн функц дээр мѳн адил ажиллана: ```js // Correct @@ -373,11 +374,11 @@ this.setState(function(state, props) { }); ``` -### State Updates are Merged {#state-updates-are-merged} +### State-ын шинэчлэлтүүд нэгдмэл {#state-updates-are-merged} -When you call `setState()`, React merges the object you provide into the current state. +`setState()` дуудах үед, React ѳгѳгдсѳн object-ыг одоогийн state-д байгаатай нэгтгэнэ. -For example, your state may contain several independent variables: +Жишээ нь, таны state олон тусдаа хувьсагч агуулсан байна: ```js{4,5} constructor(props) { @@ -389,7 +390,7 @@ For example, your state may contain several independent variables: } ``` -Then you can update them independently with separate `setState()` calls: +Тэгээд та тус тусд нь `setState()` дуудаж шинэчилж болно. ```js{4,10} componentDidMount() { @@ -407,27 +408,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`. +Ингэж нэгтгэх нь маш хязгаарлагдмал, тиймээс `this.setState({comments})` нь `this.state.posts` -ыг хѳндѳѳгүй ч `this.state.comments` -ыг бүр цоо шинээр сольж байгаа юм. -## The Data Flows Down {#the-data-flows-down} +## Ѳгѳгдлийн урсгал доош чиглэлтэй {#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. +Эцэг компонент, хүү компонент ялгаагүй аль нэг компонентийг state-тэй эсвэл state-гүйг мэдэж чадахгүй, тэгэхээр class эсвэл функц байдлаар зарлагдсан эсэх нь тѳдийлэн хамаагүй байдаг. -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. +Иймээс л state-ыг дотор нь зарладаг. Ѳѳрѳѳс нь ѳѳр хэн ч хандаж, ѳѳрчлѳх боломжгүй. -A component may choose to pass its state down as props to its child components: +Компонент мѳн ѳѳрийн state-ээ доторх компонентруугаа props-оор дамжуулж болно: ```js

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

``` -This also works for user-defined components: +Хэрэглэгчийн тодорхойлсон компонентод хүртэл ажиллана: ```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` компонент `date`-ыг props болгон авлаа гэхэд, `Clock`-ын state-ээс, эсвэл `Clock`-ын props-оос, эсвэл бүр гараар бичснийг нь мэдэхгүй: ```js function FormattedDate(props) { @@ -437,11 +438,11 @@ function FormattedDate(props) { [**Try it on 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. +Үүнийг "дээрээс-доош" буюу нэг чиглэлийн урсгал гэдэг. Ямар ч state үргэлж ямар нэг компонентод харъяалагдана. Мѳн тэр state-ээс хамаарах ѳгѳгдѳл нь DOM дээр ѳѳрѳѳс нь зѳвхѳн доош орших компонентод нѳлѳѳлж чадна. -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. +Та компонентийн модыг props-оос бүрдсэн хүрхрээ гэж ойлгож болно. Компонент бүрийн state нь ерѳнхий урсгалд нэгдэж буй бүрдэл хэсэг. Тэгээд бүгд л доошоо урсана. -To show that all components are truly isolated, we can create an `App` component that renders three ``s: +Бүх компонент биеээ даасан тусдаа байдгийг харуулахын тулд, бид `` -ыг рендэрлэдэг `App` компонент үүсгэж болно: ```js{4-6} function App() { @@ -462,6 +463,6 @@ ReactDOM.render( [**Try it on CodePen**](https://codepen.io/gaearon/pen/vXdGmd?editors=0010) -Each `Clock` sets up its own timer and updates independently. +`Clock` бүр ѳѳрѳѳ ѳѳрийнхѳѳ цагыг тохируулж тус тусдаа шинэчлэгддэг. -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 аппликейшнд компонент state-тэй болон state-гүй байх нь цаг хугацааны явцад ѳѳрчлѳгдѳж магадгүй. Гэсэн хэдийгээр та state-гүй компонентийг state-тэй компонентод эсвэл эсрэгээр нь ашиглаж болно.