React 組件生命周期

實(shí)例化

  • 一個(gè)實(shí)例初次創(chuàng)建

getDefaultProps 只會(huì)被調(diào)用一次

getInitalState 每個(gè)實(shí)例調(diào)用一次

componentWillMount 首次渲染之前被調(diào)用,可以修改state

render 創(chuàng)建虛擬DOM,表示組件輸出,必須要有的方法。只能通過(guò)this.props和this.state訪問(wèn)數(shù)據(jù)。返回null、false、任何React組件。只能有一個(gè)頂級(jí)組件,不能改變組件的狀態(tài)或者修改DOM的輸出。

componentDidMount 在真實(shí)的DOM渲染之后,可以通過(guò)this.getDOMNode()訪問(wèn)原生DOM,測(cè)量渲染的DOM元素高度,運(yùn)行jQuery

var datasource=[];

var MyComponent=React.creatClass({
    render:function(){
        return <input />;
    },
    componentDidMount: function(){
        $(this.getDOMNOde()).autocomplete({
            sources: datasource
        })
    }
})

存在期

  • 組件已渲染好,可以和它交互

componentWillReceiveprops 通過(guò)父輩組件修改props、state

componentWillReceiveProps: function(nextProps) {
    if (nextProps.checked !== undefined) {
        this.setState({
            checked: nextProps.checked
        })
    }
}

shouldComponentUpdate 優(yōu)化組件渲染,確實(shí)組件是否要渲染新的props、state

componentWillUpdate 在組件接收到新的props或者state渲染之前調(diào)用,不可在此更新state、props,要借助componentWillReceiveprops更新state

componentDidUpdate 類似componentDidMount,在此更新已渲染的DOM

銷毀&清理期

componentWillUnmountcomponentDidMount中添加的任務(wù)都要在此撤銷,如定時(shí)器、事件監(jiān)聽(tīng)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容