# 生命周期

## 旧版本

![2\_react生命周期(旧)](/files/fM3GeMDVRwuapErwny6S)

上面的生命周期图展示了不同情况的生命周期方法回调的顺序，共有四个起始点，也就是四种情况：

1. `挂载时`，也就是组件第一次初始化的时候
2. `setState()`，调用`setState()`更该状态机的时候
3. `forceState()`，调用`forceState()`方法强制更新的时候
4. `父组件render`，父组件发生渲染时，也就是调用了`render()`方法
5. 卸载，执行`componentWillUnmount()`

## 新版本

新版本可以用旧版本的钩子，如果是已经移除的钩子函数，则需要增加`UNSAFE`前缀。

![3\_react生命周期(新)](/files/UbQPaawOb0U6bp6cgii6)

三个被废弃的：

* `componentWillMount`
* `componentWilReceiveProps`
* `componentWilUpdate`

新增的：

* `getDerivedStateFromProps`，（不常用）从Props中获取一个派生的State，这是一个静态方法。

  ```javascript
  // 请求参数为props
  // 返回为state
  // 适用场景，state的状态取决于props时使用
  static getDerivedStateFromProps(props) {
    return this.state
  }
  ```
* `getSnapshortBeforeUpdate`，（不是太常用），再最后一次输出之前调用

  ```javascript
  // 包含两个参数，上一次渲染的props，上一次渲染的state
  getSnapshortBeforeUpdate(preProps, preState) {
    return xxx; // 返回值会交给最后一个生命周期 componentDidUpdate 钩子函数
  }
  ```

  \*\*使用场景：\*\*让组件在发生更改之前从DOM中捕获一些信息（比如滚动位置），并将返回值作为参数传递给`componentDidUpdate()`


---

# 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://yangsx95.gitbook.io/notes/front-end/react/sheng-ming-zhou-qi.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.
