只有class組件才有生命周期乖酬,function式的組件見沒有生命周期(生命周期其實(shí)就是里面的一些回調(diào)函數(shù))
生命周期階段
- 掛載階段
-
constructor(props)(在這里初始化state忍坷,這個只會執(zhí)行一次)砂心,如果不初始化 state 或不進(jìn)行方法綁定叠穆,則不需要為 React 組件實(shí)現(xiàn)構(gòu)造函數(shù)。
通常,在 React 中,構(gòu)造函數(shù)僅用于以下兩種情況:
通過給this.state
賦值對象來初始化內(nèi)部 state舔亭,
為事件處理函數(shù)綁定實(shí)例 - static getDerivedStateFromProps()
- render(只負(fù)責(zé)渲染,這幾個帶will的都在render之前執(zhí)行)蟀俊,如果 shouldComponentUpdate() 返回 false钦铺,則不會調(diào)用 render()和componentDidMount。
-
componentDidMount(在這個獲取到真實(shí)的DOM)
-注-:Ajax請求在componentDidMount()里做
這個即將不用:
UNSAFE_componentWillMount(即將掛載)會和static getDerivedStateFromProps()互斥
- 更新(當(dāng)組件的props或者state發(fā)生變化時觸發(fā))
- static getDerivedStateFromProps(新版本加入肢预,這里面沒有this矛洞,在實(shí)例創(chuàng)建前就已經(jīng)存在)
- shouldComponentUpdate(很重要,組件是否需要更新)
- render()
- getSnapshotBeforeUpdate()
-
componentDidMount()
這兩個即將不用:
UNSAFE_componentWillUpdate()
UNSAFE_componentWillReceiveProps(nextProps,nextState)
- 卸載
- componentWillUnmount(在這里會清除定時器等)
- 錯誤處理
- static getDerivedStateFromError()
-
componentDidcatch()
生命周期圖譜
image.png
shouldComponentUpdate()可以在這里做性能優(yōu)化
- 第一個做法,使用shouldComponentUpdate
shouldComponentUpdate (nextProps,nextState) {
return nextProps.isCompleted !== this.props.isCompleted
}
-
第二個做法烫映,利用PurComponent(純組件)沼本,是自動在shouldComponentUpdate里做了一次淺比較,所以有時候還會再做一次shouldComponentUpdate
首先需要import引入锭沟,然后在原來寫component的地方用PurComponent代替
image.png
如果想要把狀態(tài)切換做成state方式:
// TodoItem.js
export default class TodoItem extends Component {
constructor () {
super()
this.state = {
completedText: ''
}
}
shouldComponentUpdate (nextProps,nextState) {
return nextProps.isCompleted !== this.props.isCompleted
}
static getDerivedStateFromProps (props) {
return {
completedText: props.isCompleted ? '完成' : '未完成'
}
}