美文网首页
State & 生命周期

State & 生命周期

作者: ShinPlus | 来源:发表于2019-07-23 09:54 被阅读0次
    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, Rails!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        );
      }
    }
    
    
    ReactDOM.render(
      <Clock />,
      document.getElementById('root')
    );
    

    相关文章

      网友评论

          本文标题:State & 生命周期

          本文链接:https://www.haomeiwen.com/subject/wbgnlctx.html