2019-09-02 React 生命周期

173 阅读2分钟

上图

React声明周期图


现在直接看图可能会感觉比较复杂,但是不要慌张

  1. Initialization:初始化阶段。
  2. Mounting: 挂载阶段。
  3. Updation: 更新阶段。
  4. Unmounting: 销毁阶段

例如(初始化和挂载阶段):

class Text extends Component {
    constructor(props) {        
        super(props);        
        this.state = {  }    
    }    
    
    componentWillMount(){        
        console.log('will -------')    
    }    

    componentDidMount(){        
        console.log('did -------')    
    }    

    render() {        
        return (  );    
    }
}


  1. Initialization:初始化阶段。
    1. constructor我们叫构造函数,它是ES6的基本语法。虽然它和生命周期函数的性质一样,但不能认为是生命周期函数。
  2. Mounting: 挂在阶段。
    1. componentWillMount : 在组件即将被挂载到页面的时刻执行。
    2. render : 页面state或props发生变化时执行。
    3. componentDidMount : 组件挂载完成时被执行。


例如(更新和销毁阶段):

//Test1
class Test1 extends Component {    
    constructor(props) {        
        super(props);        
        this.state = {  }    
    }    

    componentWillMount(){        
        console.log('will -------')    
    }    

    componentDidMount(){        

        console.log('did -------')    
    }    

    shouldComponentUpdate(){        
        console.log('1 shouldComponentUpdate -------')       
        return true    
    }    

    componentWillUpdate(){        
        console.log('2 componentWillUpdate -------')    
    }    

    componentDidUpdate(){        
        console.log('4 componentDidUpdate -------')    
    }            

    render() {        
        console.log('3 render --------')         
        return ( <Test2 /> );    
    }
}

//Test2
class Test2 extends Component {    
    constructor(props) {        
        super(props);        
        this.state = {  }    
    }        
    //组件第一次存在于Dom中,函数不会被执行。 如果已经存在Dom中,函数才会被执行    
    componentWillReceiveProps(){        
        console.log('child componentWillReceiveProps -------')    
    }    

    componentWillUnmount(){        
        console.log('end componentWillUnmount -------')    
    }        
render() {         return (  );    }}


  1. Updation: 更新阶段。
    1. shouldComponentUpdate函数会在组件更新之前,自动被执行。
      它要求返回一个布尔类型的结果,必须有返回值,例子就直接返回的 true
    2. componentWillUpdate在组件更新之前,但shouldComponenUpdate之后被执行。但是如果shouldComponentUpdate返回false,这个函数就不会被执行了。
    3. componentDidUpdate在组件更新之后执行,它是组件更新的最后一个环节。
    4.  componentWillReceiveProps在子组件接收了props,这时候函数就可以被执行了。
  2. Unmounting: 销毁阶段
    1. componentWillUnmount,它是在组件去除时执行


可能大家在使用低版本的React 的生命周期时,日志会出现警告。

2933756055-5d54177951edf_articlex (800×125)

可做参考:segmentfault.com/a/119000002…


建议:大家自己敲一敲代码 ,加深记忆力,又可以对生命周期的理解更深一层。


前端mock线上模拟:EasyMock  


推荐npm 库:

  1. axios(ajax)请求Mock数据
  2. react-transition-group 动画库