React生命周期详解

这篇文章我们将讨论React组件的生命周期

一、组件的生命周期分成三个状态:
  • Mounting:已挂载到真实DOM
  • Updating:正在重新渲染
  • Unmounting:已移出真实DOM
二、生命周期方法:
Mounting
  • construtor() 组件的构造函数在挂载之前调用
  • conponentWillMount() 在渲染前调用
  • render() 组件初次渲染
  • componentDidMount() 第一次渲染后调用,可以通过findDOMNode() 来进行访问。如果你想和其他js框架一起使用,可以在这个方法调用setTimeout,setInerval()或者发送AJAX请求等操作(防止异步操作阻塞UI)
Updating
  • componentWillRecevieProps() 组件接收到一个新的props时被调用。这个方法在初始化render时不会调用
  • shouldComponentUpdate() 返回一个布尔值。在组件接收到新的props或者state时被调用。初始化时不会调用
  • componentWillUpdate() 组件接收到新的props或者state但还没有render时被调用。初始化时不会调用
  • render() 重新渲染
  • componentDidUpdate() 在组件完成更新后立即调用。初始化时不会调用
Unmounting
  • componentWillUnmount() 组件从DOM中移出的时候立即调用

三、在渲染前可以使用的部分API

  • getDefaultProps 设置默认的prop值
  • getInitialState 设置初始state
四、Demo

demo1

    <script type="text/jsx">
        var MessageBox = React.createClass({
            getDefaultProps:function(){
                console.log('getDefaultProps');
                return {};
            },
            getInitialState:function(){
                console.log('getInitialState');
                return {
                    count: 0,
                }
            },
            componentWillMount:function(){
                console.log('componentWillMount');

            },
            componentDidMount:function(){
                console.log('componentDidMount')
                var self = this;

                this.timer = setInterval(function(){
                    self.setState({
                        count: self.state.count + 1,
                    })
                },1000);
                console.log(this.getDOMNode(), this.state.count);
            },
            componentWillUnmount: function(){
                alert('you are tring to kill me !! ')

                clearInterval(this.timer);

            },
            killMySelf: function(){
                React.unmountComponentAtNode(  document.getElementById('app') );
            },
            render:function(){  
                console.log('渲染')
                return ( 
                    <div>
                        <h1 > 计数: {this.state.count}</h1> 
                        <button onClick={this.killMySelf}>卸载掉这个组件</button>
                        <Submessage/>
                    </div>
                )
            }
        });

        var Submessage = React.createClass({
            render:function(){
                return (
                    <h3>写代码很有意思</h3>
                )
            }
        });


        var messageBox = React.render( <MessageBox/>, 
            document.getElementById('app')
        )


    </script>

demo2

    <script type="text/jsx">
        var MessageBox = React.createClass({
            getInitialState:function(){
                return {
                    count: 0,
                }
            },
            getDefaultProps:function(){
            },
            shouldComponentUpdate:function(nextProp,nextState){
                console.log('shouldComponentUpdate');
                if(nextState.count > 10) return false;

                return true;
            },
            componentWillUpdate:function(nextProp,nextState){
                console.log('componentWillUpdate');
            },
            componentDidUpdate:function(){
                console.log('componentDidUpdate');
            },
            killMySelf: function(){
                React.unmountComponentAtNode(  document.getElementById('app') );
            },
            doUpdate:function(){
                this.setState({
                    count: this.state.count + 1,
                });
            },
            render:function(){  
                console.log('渲染')
                return ( 
                    <div>
                        <h1 > 计数: {this.state.count}</h1> 
                        <button onClick={this.killMySelf}>卸载掉这个组件</button>
                        <button onClick={this.doUpdate}>手动更新一下组件(包括子组件)</button>
                        <Submessage count={this.state.count}/>
                    </div>
                )
            }
        });

        var Submessage = React.createClass({
            componentWillReceiveProps:function(nextProp){
                console.log('子组件将要获得prop');
                
            },
            shouldComponentUpdate:function(nextProp,nextState){
                if(nextProp.count> 5) return false;
                return true;
            },
            render:function(){
                return (
                    <h3>当前计数是:{this.props.count}</h3>
                )
            }
        });


        var messageBox = React.render( <MessageBox/>, 
            document.getElementById('app')
        )
    </script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这一部分内容一直一知半解,最近发现一篇文章,非常好的解释了生命周期的问题,留存在这里,以备后查! 简介 一个rea...
    春木橙云阅读 1,034评论 0 5
  • 上面的这幅图已经很好地诠释一个react组件的生命周期,所以认真看图!认真看图!认真看图! 一、getDefaul...
    好大一颗星阅读 367评论 0 2
  • Mounting / 挂载阶段 getDefaultProps->getInitialState->compone...
    TonyerX阅读 417评论 0 0
  • 组件生命周期,组件本质上是状态机 组件把状态和结果一一对应起来 组件中有state状态 和 props属性,属性是...
    mannysys阅读 418评论 0 0
  • Each component has several "lifecycle methods" that you c...
    暮落晨曦阅读 529评论 0 0

友情链接更多精彩内容