# 3.2 lifecycle

![](/files/-M3Pc2kPc7lSFIYOYcIx)

**Mounting(載入)**

元件正要被載入DOM中階段

* **componentWillMount()**\
  這個方法是在我們元件第一次要render到畫面前會執行，整個生命過程只會執行一次，基本上這個方法不會有太多用到的地方，不在此階段進行AJAX 主要是因為，沒辦法很確定你對資料的請求能在畫面render之前處理好。
* **componentDidMount()**\
  當畫面render完畢後就會馬上觸發該方法，大部分AJAX要進行處理都是在這個方法裡面調用。

**Updating(更新)**

遇到state的改變然後重新re-render階段

* **componentWillRecieveProps(nextProps)**\
  這個方法並不會再初始化的時候觸發，只有在元件接收到新的props才會調用，而舊的props是可以用this.props來調用，所以你可以在這個方法中去比較新舊props的不同並且去調用setState()，不過在這階段並不會重新render。
* **shouldComponentUpdate(nextProps, nextState)**\
  這個方法回傳的是一個布林值，讓你去比較新舊state跟新舊props是否相同，並且決定要不要去做re-render。
* **componentWillUpdate**\
  到了這個方法就是更新前的階段了，簡單來說就是在你接收到新的state之後要進行re-render前的這個時間點，你想要執行什麼都是在這個方法來調用。在這個方法中你不能去調用setState()，那會讓你的程式陷入initial loop(無窮迴圈)，因為你在這個階段setState就表示你要更新，他就又會跳回來這個更新前的方法，一直持續下去。
* **componentDidUpdate**\
  當元件re-render更新完後的時間點就是調用這個方法的時候，會用到的東西其實跟前面的**componentDidMount()**&#x5DEE;不多，當你的畫面都render出來，你可能想要去對一些DOM來進行操控，那這些就可以寫在這個方法裡面。打個比方來說你可能在初始階段的**componentDidMount()**&#x6709;用JQuery來做一些效果，所以一旦當你state改變後並重新render完，你還想要做出那些效果，那你就必須在這個方法裡面再寫一次。

**Unmounting(卸載)**

元件要從DOM移除階段

* **componentWillUnmount**\
  這個方法會在元件從DOM移除之後馬上調用，功用就只是用來清除一些可能之前有調用的函數之類的。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack1in.gitbook.io/font-end/3.-react/3.2-lifecycle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
