React生命周期调用函数介绍

React生命周期调用函数介绍

 
var MainComponent = React.createClass({
    //设置数据的默认值
    getDefaultProps: function () {
        console.log("getDefaultProps");
        return {name: 'null'};
    }
    //在组件加载之前调用一次,返回值作为this.state的初始值
    , getInitialState: function () {
        console.log("getInitialState");
        return {count: 0};
    },
    //在完成首次渲染之前调用
    componentWillMount: function () {
        console.log("componentWillMount");
    },
    //必选的方法,创建虚拟DOM
    //只能通过this.state和this.props访问数据
    //可以返回null,false或任何React组件
    //只能出现一个顶级组件(不能返回数组)
    //不能改变组件的状态
    //不能修改DOM的输出

    //一、
    render:function () {
        console.log("render");
        return <div>MainComponent</div>
    },
    //二、
    render: ()=> {
        console.log("render");
        return <div>MainComponent</div>
    },
//    真实的DOM被渲染出来后调用,在该方法中可通过this.getDOMNode()访问到真实的DOM元素
    componentDidMount: function () {
        console.log("componentDidMount");
    }
    ,
//    组件接收到新的props时调用,并将其作为参数nextProps使用
    componentWillReceiveProps: function (nextProps) {
        console.log("componentWillReceiveProps");
        if (nextProps.bool) {
            this.setState({
                bool: true
            })
            ;
        }
    },
//组件是否需要渲染新的props或state,返回false表示跳过后续的生命周期方法,通常不需要使用,以免出现bug
    shouldComponentUpdate: function () {
        return true;
    },
    //接受到新的props或者state后,进行渲染之前调用
    componentWillUpdate: function () {
        console.log("componentWillUpdate");
    },
//    完成渲染新的props或者state调用,此时可以访问到新的DOM元素 
    componentDidUpdate: function () {
        console.log("componentDidUpdate");
    }
    //组件被移除之前调用,可以做一些清理工作,在conponentDidMount方法中添加的所有任务都需要在该方法中撤销
    , componentWillUnmount: function () {
        console.log("componentWillUnmount");
    }

});

ReactDOM.render(<MainComponent/>, document.getElementById("content"));

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值