react 初探:类组件、状态和生命周期

react 除了提供函数式组件外,还提供了类组件,类组件提供了状态属性,下面一起吧之前的函数组件转换成类组件。

/*
  类组件定义
*/
class Clock extends React.Component{
    render(){
      return (
        <div>
            <h1>Hello,World</h1>
            <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
        </div>
      );
    }
}

替换 render() 方法中的 this.props.date 为 this.state.date

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

添加类构造函数

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

经过修改之后的最终代码如下:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

这里写图片描述
这样,当调用Clock组件时,能够实现页面上的具体时刻。但是这样做还是有些问题,无法做到每秒钟都更新组件,这里不能像上一章节,直接采用setInterval(tick, 1000);的方式来进行每秒钟更新,需要使用类组件提供的生命周期函数才可以。

类的生命周期

componentDidMount() 钩子在组件输出被渲染到 DOM 之后运行。我们将计时器的设置放在生命周期函数内。

 componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

当Clock组件DOM被清除时需要将计时器也销毁,需要在结束生命周期函数中将该计时器销毁。

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

最后,贴出整个流程的完整代码:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

这里写图片描述
这里写图片描述

可以做到美妙都刷新DOM。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值