> For the complete documentation index, see [llms.txt](https://jack1in.gitbook.io/font-end/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack1in.gitbook.io/font-end/3.-react/3.2-lifecycle.md).

# 3.2 lifecycle

![](https://2919068548-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lh-g1QkhJbS3wly_4sc%2F-M3PbvKMdzVpHD_6CyFN%2F-M3Pc2kPc7lSFIYOYcIx%2Flifecycle.png?alt=media\&token=e781f811-04f1-4c57-96d8-7f5e4d7d2709)

**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移除之後馬上調用，功用就只是用來清除一些可能之前有調用的函數之類的。
