react組件的生存周期

生存周期圖

  • 從組件創(chuàng)建到銷毀的整個過程
生存周期圖.png

完整的生命周期鉤子函數(shù)

  • 鉤子函數(shù)就是一個事件,在相應的階段觸發(fā)的對應的函數(shù)。

創(chuàng)建階段(mount)

  • constructor:構(gòu)造函數(shù),這個時候還不算時個組件,只是class自身的初始化
  • getDerivedStateFromProps:檢查需要更新的狀態(tài)
  • render:初始渲染
  • componentDidMount:組件創(chuàng)建完成,并已掛載到DOM上,比較常用。
class Cmp extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            a:1
        }
        console.log('constructor');
    }
    componentDidMount() {
        console.log('創(chuàng)建了')
    }
    render(){
        console.log('渲染了');
        return (
            <div><p>{this.state.a}</p></div>
        )
    }
}
ReactDOM.render(<Cmp></Cmp>,document.getElementById('root'))
// 輸出:
// constructor
// 渲染了
// 創(chuàng)建了

更新階段(updata)

  • getDerivedStateFeomProps:檢查組件需要更新的狀態(tài)
  • shouldComponentUpdate:確定組件是否需要更新,需要使用return值,ture或者false;沒有返回值的話會報錯;

Warning: Cmp.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

  • render渲染
  • componentDidUpdate:組件渲染完成
class Cmp extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            a:1
        }
        console.log('constructor');
    }
    componentDidMount() {
        console.log('創(chuàng)建了')
    }
    componentDidUpdate() {
        console.log('didUpdate')
    }
    shouldComponentUpdate(nextProps, nextState) {
        console.log(nextProps, nextState);
        //這里可以寫相關的判斷,決定是否進行渲染;
        return true
    }
    
    
    fn(){
        this.setState({
            a:this.state.a +1
        })
    }
    render(){
        console.log('渲染了');
        return (
            <div>
                <p>{this.state.a}</p>
                <input type="button" value="按鈕" onClick={this.fn.bind(this)}></input>
            </div>
        )
    }
}
ReactDOM.render(<Cmp></Cmp>,document.getElementById('root'))

結(jié)合父子組件、組件傳值、componentDidMountcomponentDidUpdate、shouldComponentUpdate的應用實例

class Parent extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            id:1
        }
    }
    fn(){
        this.setState({
            id:this.state.id +1
        })
    }
    render(){
        return (
            <div>
                <p>{this.state.id}</p>
                <input type="button" value="按鈕" onClick={this.fn.bind(this)}></input>
                <Child id={this.state.id}></Child>
            </div>
        )
    }
}
class Child extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            name:'',
            age:''
        }
    }
    componentDidMount() {
        console.log('componentDidMount')
        this.updata(this.props.id)
    }
    componentDidUpdate(prevProps, prevState) {
        console.log('componentDidUpdate')
        if(prevProps.id != this.props.id){
            this.updata(this.props.id)
        }
    }
    
    shouldComponentUpdate(nextProps, nextState) {
        return (nextProps.id != this.props.id || nextState.name != this.state.name)
    }
    updata(id){
        fetch(`../data/data${id}.txt`).then(res=>{
            res.json().then(data=>{
                this.setState({
                    name:data.name,
                    age:data.age
                })
            })
        })
    }
    render(){
        return (
            <div>
                <p>ID:{this.props.id}</p>
                <p>姓名:{this.state.name} 年齡:{this.state.age}</p>
            </div>
        )
    }
}
ReactDOM.render(<Parent></Parent>,document.getElementById('root'))

銷毀階段(Unmount)

  • componentWillUnmount組件銷毀的回調(diào)函數(shù)
class Parent extends React.Component{
    constructor(...args){
        super(...args)
        this.state={
            id:true
        }
    }
    fn(){
        this.setState({
            id:!this.state.id
        })
    }
    render(){
        return (
            <div>
                <p>{this.state.id}</p>
                <input type="button" value="按鈕" onClick={this.fn.bind(this)}></input>
                {this.state.id?(<Child></Child>):''}
            </div>
        )
    }
}
class Child extends React.Component{
    constructor(...args){
        super(...args)
    }
    componentDidMount() {
        console.log('didmount')
    }
    componentWillUnmount() {
        console.log('Unmount');
    }
    render(){
        return (
            <div>子組件</div>
        )
    }
}
ReactDOM.render(<Parent></Parent>,document.getElementById('root'))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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