React 的组件生命周期

   React组件的state或者props发生改变后会导致这个组件重新渲染,此时DOM也会有相应的变化。其中只有Render方法在上一篇博文中提到过,就是DOM渲染时的方法。当然,只有这个方法是不够的哦!,引文在实际的开发中,开发者们需要对组件的各个阶段进行控制,这样就可以高效的进行开发了,为此,就有了React的组件生命周期的概念。

   对于一个基本的React组件,可以把每一个React组件的生命周期分为初始化、挂载、更新、卸载四个阶段,在React的这四个阶段中提供了不同的方法,以方便开发者有足够控制权对组件进行控制。

  • 组件初始化阶段的方法:getDefaultProps(),getInitialState();
  • 组件挂载阶段的方法有:componentWillMount(),render(),componentDidMount();
  • 组件更新的方法:shouldComponentUpdate(),componentWillUpdate()、render()、componentDidUpdate()、componentWillReceiveProps();
  • 组件卸载的方法:componentWillUnmount();

注意:在组件的挂载阶段并不会调用组件更新阶段的这些方法,也就是初次渲染过程中更新阶段方法是不可用,因此开发者不应该将处于初次渲染就使用的方法在更新阶段来使用,这是非常不明智的做法。

        shouldComponentUpdate()方法应该返回一个布尔值,如果返回值为true就继续更新这个组件,反之,如果返回值为false,这个组件将不更新,也就是说,此时,componentWillUpdate()、render()、componentDidUpdate()方法是不会被调用的。

   为理解生命周期的概念,可以使用一个代码来进行更好的说明:

App.js

//引入react
import React ,{Component} from 'react';


//引入样式文件
import './App.css';

//构建APP类



class App extends Component{
    constructor(){
    super();
    
    //定义初始化state
    this.state={name:1234}
}
    
    //组件将要挂载
    componentWillMount(){
        
        console.log('willMount');
    }
    
    //组件挂载完成
    componentDidMount(){
        console.log('didmount');
    }
    
    //组件是否应该更新
    shouldComponentUpdate(){
        console.log('shouldupdate');
        return true;
    }
    
    //组件将要更新
    componentWillUpdate(){
        console.log('will update');
        
    }
    
    //组件更新完成
    componentDidUpdate(){
        
        console.log('didupdate');
    }
    
    
    //定义render方法
    
    render(){
        
        console.log('render');
        
        
        
        
        return (
            
            <div className='App'>
            
            <input type="button" onClick={ () => {this.setState({name:2345})}} value="Change"  />
            
            
            </div>
            
        );
        
        
        
    }
}



export default App;

没点击按钮时在浏览器中的初始效果:

结果可以看出,处于组件更新阶段的方法都没有被调用

单击按钮后,组件的state改变了,因此会造成这个组件重新渲染

猜你喜欢

转载自www.cnblogs.com/jiguiyan/p/11227307.html