App下載

在前端react框架中生命周期有那幾個(gè)階段?

猿友 2021-06-08 15:22:55 瀏覽數(shù) (2390)
反饋

當(dāng)我們?cè)趯W(xué)習(xí)前端語言框架的時(shí)候,我們除了知道它是干什么的還要知道這個(gè)框架的生命周期;那么今天我們就來講講“在前端react框架中生命周期有那幾個(gè)階段”吧!


在react框架的生命周期中廣義上分為:掛載、渲染、卸載這三個(gè)階段。所以我們可以把React框架的生命周期分為掛載卸載過程和更新過程,生命周期圖如下:

生命周期圖

1.掛載卸載過程

(1).constructor():

這個(gè)方法是用來完成 React 數(shù)據(jù)的一個(gè)初始化,還接受?props?和?context?這兩參數(shù),如果我們想在函數(shù)內(nèi)部使用這兩參數(shù)時(shí),就必須要使用?super()?進(jìn)行傳入?yún)?shù);否則會(huì)導(dǎo)致this指向錯(cuò)誤。

(2).componentWillMount():

這個(gè)方法的話一般比較少用,比較多的是在服務(wù)端的時(shí)候使用。

(3).componentDidMount():

當(dāng)組件第一次渲染完成的時(shí)候dom節(jié)點(diǎn)生成,就可以在這里調(diào)用ajax的請(qǐng)求,等到返回setstate數(shù)據(jù)之后組件會(huì)重新的渲染。

(4).componentWillUnmount():

這個(gè)方法是用來進(jìn)行組件的一個(gè)卸載和數(shù)據(jù)的銷毀的。有時(shí)候我們?cè)趫?zhí)行的時(shí)候會(huì)碰到下面這個(gè)警告,是因?yàn)槲覀兊慕M件中的Ajax請(qǐng)求返回的?setstate?在我們執(zhí)行銷毀的時(shí)候還沒有請(qǐng)求完成所報(bào)的警告!

Can only update a mounted or mounting component. This usually      means you called setState() on an unmounted component. This is a   no-op. Please check the code for the undefined component.

解決方法如下代碼:

componentDidMount() {
    this.isMount === true
    axios.post().then((res) => {
    this.isMount && this.setState({   // 增加條件ismount為true時(shí)
      aaa:res
    })
})
}
componentWillUnmount() {
    this.isMount === false
}
2.更新過程

(1).componentWillReceiveProps (nextProps):

這個(gè)方法用的比較多的是在接受父組改變之后的props需要重新渲染組件的時(shí)候。下面是通過?nextProps?和?this.props?對(duì)比,從而重新渲染的代碼和注釋。

  componentWillReceiveProps (nextProps) {
    nextProps.openNotice !== this.props.openNotice&&this.setState({
        openNotice:nextProps.openNotice
    },() => {
      console.log(this.state.openNotice:nextProps)
      //將state更新為nextProps,在setState的第二個(gè)參數(shù)(回調(diào))可以打         印出新的state
  })
}

(2).shouldComponentUpdate(nextProps,nextState):

這個(gè)方法主要用于在性能部分的優(yōu)化,還可以通過?return false?阻止組件的更新。

(3).componentWillUpdate (nextProps,nextState):

在這個(gè)方法中,當(dāng)?shouldComponentUpdate?返回?為true?以后呢,組件就會(huì)進(jìn)入重新渲染的流程,進(jìn)入到這個(gè)方法時(shí),我們這個(gè)方法里同樣可以拿到?nextProps?和?nextState?。

(4).componentDidUpdate(prevProps,prevState):

這個(gè)方法的作用是當(dāng)組件更新完成之后,react 只有在第一次初始化完成之后會(huì)進(jìn)入?componentDidmount?;后面的每次重新渲染后都會(huì)進(jìn)入?componentDidUpdate(prevProps,prevState)?這個(gè)生命周期,而且在這個(gè)周期中可以拿到?prevProps?和?prevState?,就是在更新前的?props?和?state?。

(5).render():

render 這個(gè)函數(shù)會(huì)插入 jsx 生成的 dom 結(jié)構(gòu)中,從而生成一份虛擬 dom 樹,而且在每一次組件更新時(shí),還會(huì)通過其 diff 的算法比較更新前后的 DOM 樹,找到最小的而且還有差異的 DOM 節(jié)點(diǎn)重新渲染。


總結(jié):

這就是有關(guān)于“在前端react框架中生命周期有那幾個(gè)階段”的個(gè)人分析,當(dāng)然隨著不斷地更新還會(huì)有更多的知識(shí)加入,如果小伙伴們有更好的一些想法也可以和大家一起分享,一起成長(zhǎng)進(jìn)步。更多的想過知識(shí)可以在W3cschool中進(jìn)行學(xué)習(xí)和了解。


0 人點(diǎn)贊