react_basic(9)

本文通过一个计数按钮的示例,详细介绍了React中组件的生命周期方法,包括挂载阶段的componentWillMount和componentDidMount,更新阶段的componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate和componentDidUpdate,以及卸载阶段的componentWillUnmount。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//生命周期

var Button = React.createClass({
      getInitialState: function() {
        return {
          data:0
        };
      },
      setNewNumber: function() {
        this.setState({data: this.state.data + 1})
      },
      render: function () {
          return (
             <div>
                <button onClick = {this.setNewNumber}>INCREMENT</button>
                <Content myNumber = {this.state.data}></Content>
             </div>
          );
        }
    })
    var Content = React.createClass({
      componentWillMount:function() {
          console.log('Component WILL MOUNT!')
      },
      componentDidMount:function() {
           console.log('Component DID MOUNT!')
      },
      componentWillReceiveProps:function(newProps) {
            console.log('Component WILL RECEIVE PROPS!')
      },
      shouldComponentUpdate:function(newProps, newState) {
            return true;
      },
      componentWillUpdate:function(nextProps, nextState) {
            console.log('Component WILL UPDATE!');
      },
      componentDidUpdate:function(prevProps, prevState) {
            console.log('Component DID UPDATE!')
      },
      componentWillUnmount:function() {
             console.log('Component WILL UNMOUNT!')
      },


        render: function () {
          return (
            <div>
              <h3>{this.props.myNumber}</h3>
            </div>
          );
        }
    });
      ReactDOM.render(


         <div>
            <Button />
         </div>,
        document.getElementById('example')                     //刷新:Component   WILL   MOUNT!      Component   DID    MOUNT!

点击之后:Component   WILL   RECEIVE PROPS!
      Component   WILL   UPDATE!
                                                                                                            Component     DID    UPDATE!
      );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值