《React从入门到放弃》第三集 生命周期

     这一集简单点:生命周期到三个阶段:Mounting(初始化数据期)、Updating(更新期)、Unmounting(销毁期)。

       看下面到代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
    <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>

    <script type="text/babel">

        var HelloWorld = React.createClass({

            /*  一、实例化期   */
            getDefaultProps:function () {
                console.log('1. getDefaultPros 获取默认的props');
                return{
                    name:"SKHon"
                }
            },

            getInitialState:function () {
                console.log("2. getInitialState 设置状态机");
                return{
                    
                }
            },

            componentWillMount:function() {
                console.log('3. componentWillMout 完成首次渲染前调用【注】这是在渲染前,修改state的最后一次机会')
            },

            render:function () {
                return(
                    <div>
                        <button onClick={this.showName}>点击</button>
                        <div>{this.props.name}</div>
                    </div>
                )
            },

            componentDidMount:function() {
                console.log('4. componentDidMount render渲染后的操作 【注】react运行在服务端时,该方法不被调用' )
            },

            showName:function () {

                console.log(this.props.name);
            },
            /*  二、存在期 (也叫修改期)  */
            componentWillReceiveProps:function(newProps) {
                this.props.name="aaa";
                console.log('组件渲染后,当组件接收到新的props时被调用')
            },

            shouldComponentUpdate:function(newProps, newState) {
                /*组件渲染后(即执行完render),接收到新的state或props时被调用*/
                return true;
            },

            componentWillUpdate:function(nextProps, nextState) {
                console.log('即将发生重新渲染前调用该方法');
            },

            componentDidUpdate:function(prevProps, prevState) {
                console.log('在组件更新之后操作DOM元素调用该方法')
            },

            /*  三、销毁期  */
            componentWillUnmount:function() {
                console.log('组件被卸载前调用')
            }

        })

        ReactDOM.render(
            <HelloWorld />,
            document.getElementById("app")
        )
    </script>
</head>
<body>
<div id="app"></div>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值