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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/256391.html
標籤:其他
下一篇:JS實作五子棋界面設計
