zoukankan      html  css  js  c++  java
  • React 生命周期 constructor->componentWillMount->render->componentDidMount->componentWillUnmount

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <title>React 生命周期 constructor->componentWillMount->render->componentDidMount->componentWillUnmount</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </head>
    <body>
    <div id="root"></div>
    <script type="text/babel">
    class Clock extends React.Component {
      constructor () {
        super()
        this.state = {
          date: new Date()
        }
        console.log('construct')
      }
      componentWillMount () {
        this.timer = setInterval(() => {
          this.setState({ date: new Date() })
        }, 1000)
        console.log('component will mount')
      }
      componentDidMount () {
        console.log('component did mount')
      }  
      componentWillUnmount () {
        clearInterval(this.timer)
        console.log('component will unmount')
      }
      render () {
        console.log('render')
        return (
          <div>
            <h1>
              <p>现在的时间是</p>
              {this.state.date.toLocaleTimeString()}
            </h1>
          </div>
        )
      }  
    }
    
    class Index extends React.Component {
      constructor () {
        super()
        this.state = { isShowClock: true }
      }
    
      handleShowOrHide () {
        this.setState({
          isShowClock: !this.state.isShowClock
        })
      }
    
      render () {
        return (
          <div>
            {this.state.isShowClock ? <Clock /> : null }
            <button onClick={this.handleShowOrHide.bind(this)}>
              显示或隐藏时钟
            </button>
          </div>
        )
      }
    }
    ReactDOM.render(
      <Index />,
      document.getElementById('root')
    );
    </script>
    </body>
    </html>
  • 相关阅读:
    手写堆排序和归并排序
    海量数据处理
    HDU 1532 --&&-- POJ1273 dinic 算法
    POJ 3159 最短路 SPFA
    POJ 1459 网络流 EK算法
    8.14比赛j题 http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87813#overview
    单链表---邻接表
    poj 1273 ---&&--- hdu 1532 最大流模板
    HDU 2603 二分匹配
    UVA 796 连通图求桥
  • 原文地址:https://www.cnblogs.com/xutongbao/p/9924780.html
Copyright © 2011-2022 走看看