react生命週期分爲4個階段:
掛載時(4個),更新時(5個),卸載時(1個),錯誤處理階段(2個)。一共有12個鉤子。
1.掛載時階段(4個鉤子):
-
constructor()
加載時調用一次,可以實現:初始化state,爲事件處理函數綁定實例。
constructor(props) {
super(props);
// 不要在這裏調用 this.setState()
this.state = { counter: 0 }; //初始化state。
this.handleClick = this.handleClick.bind(this);
}
-
static getDerivedStateFromProps(props, state)
在組件每次更新時會調用,讓組件在props變化時更新state,每次接收新的props之後都會返回一個對象作爲新的state,如果返回null,則不更新任何內容。
-
render()
類組件中唯一必須實現的方法,創建虛擬dom樹,更新dom樹都在此進行。
-
componentDidMount()
組件掛載之後調用,只調用一次。一般在這裏請求數據。
2.更新時階段(5個鉤子):
-
static getDerivedStateFromProps(props, state)
在調用 render 方法之前調用,並且在初始掛載及後續更新時都會被調用。它應返回一個對象來更新 state,如果返回 null 則不更新任何內容。
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// 當傳入的type發生變化的時候,更新state
if (type !== prevState.type) {
return {
type,
};
}
// 否則,對於state不進行任何操作
return null;
}
-
shouldComponentUpdate(nextProps, nextState)
當 props 或 state 發生變化時,在渲染前調用,return true就會更新dom,return false能阻止更新。 僅作爲性能優化的方式而存在。
-
render()
render() 函數應該爲純函數,這意味着在不修改組件 state 的情況下,每次調用時都返回相同的結果,並且它不會直接與瀏覽器交互。保持 render() 爲純函數,可以使組件更容易思考。
-
getSnapshotBeforeUpdate(prevProps, prevState)
在最近一次的渲染提交到 DOM 節點之前調用,返回一個值,作爲componentDidUpdate的第三個參數。它使得組件能在發生更改之前從 DOM 中捕獲一些信息(例如,滾動位置)。
-
componentDidUpdate(prevProps, prevState, snapshot)
會在更新後會被立即調用,首次渲染不會執行此方法。 當組件更新後,可以在此處對 DOM 進行操作、 進行網絡請求 。
3.卸載時階段(1個鉤子)
-
componentWillUnmount()
在組件卸載及銷燬之前直接調用, 在此方法中執行必要的清理操作,例如,清楚timer,取消網絡請求等等。
4.錯誤處理階段(2個鉤子)
-
static getDerivedStateFromError(error)
在渲染階段調用,它將拋出的錯誤作爲參數,並返回一個值來更新state,不允許執行副作用。
-
componentDidCatch(error, info)
在提交階段被調用,用於記錄錯誤,允許執行副作用。
副作用:(一個函數在執行過程中產生了外部可觀察的變化,比如:修改全局變量,修改傳參,console.log()等外部可觀察它的變化。)
注意:還有三個生命週期方法已經過時,在react17版本後會被淘汰,但現在仍然有效,分別是:UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps(nextProps)、UNSAFE_componentWillUpdate(nextProps, nextState)