React(17.0版本)生命周期概述


React17版本的生命周期概述。

掛載

示例代碼在下方。

當組件實例被創建並插入DOM的時候,其生命周期被調用順序如下:

  1. constructor(props) - 初始化state和為事件處理函數綁定實例;
  2. static getDerivedStateFromProps(props, state) - 當state的值在任何時候都取決於props時使用,返回一個對象來更新state,返回null則不更新;
  3. render() - 渲染React組件;
  4. componentDidMount() - 組件掛載后調用,一個生命周期內僅一次;
    25c6aad22567e8309665ac3318ff93c2.jpg

更新

當組件的props或state發生變化時會觸發更新。組件更新的生命周期順序如下:

  1. static getDerivedStateFromProps(props, state);
  2. shouldComponentUpdate(nextProps, nextState) - 根據更新后的state或props判斷是否重新渲染DOM,返回值為布爾值,常用來性能優化;
  3. render();
  4. getSnapshotBeforeUpdate(prevProps, prevState) - 是的組件能在發生改變之前從DOM中捕獲一些信息(如滾動位置),返回值作為componentDidUpdate的第三個參數;
  5. componentDidUpdate(prevProps, prevState, snapshot) - state或props更新后調用
    33ae2b2a3ebfd7560d78a33f7686251d.jpg

卸載

  • componentWillUnmount() - 組件銷毀或卸載時調用;
    9fb18e381ab8e8204fcdd955ebaca1bd.jpg

錯誤處理

  • static getDerivedStateFromError(callback) - 后代組件跑出錯誤時調用,並返回一個值以更新state;
  • componentDidCatch(error, info) - 后代組件拋出錯誤后調用,參數info包含有關組件錯誤的棧信息;

其它

  • setState();
  • forceUpdate(callback) - 組件強制更新,會跳過shouldComponentUpdate;

示例

import * as React from "react";

export class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1
};
console.log("1. constructor");
}
static getDerivedStateFromProps(props, state) {
console.log("2. getDerivedStateFromProps");
return {
count: props.count
};
}
componentDidMount() {
console.log("3. componentDidMount");
}
shouldComponentUpdate() {
console.log("4. shouldComponentUpdate");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("5. getSnapshotBeforeUpdate");
return null;
}
componentDidUpdate(props, state, snapshot) {
console.log("6. componentDidUpdate");
console.log("snapshot:", snapshot);
}
componentWillUnmount() {
console.log("7. componentWillUnmount");
}
render() {
console.log("0. render");
const { count } = this.state;
return (
<ul>
<li>state: {count}</li>
<li>props: {count}</li>
</ul>
);
}
}
 

完整周期:
8ae37f7af5eb77ec7627ec5a3220286e.jpg

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM