React 生命周期 constructor->componentWillMount->render->componentDidMount->componentWillUnmount

React 生命周期 constructor->componentWillMount->render->componentDidMount->componentWillUnmount1

在这里插入图片描述
在这里插入图片描述

<!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/[email protected]/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>

  1. 转自 徐同保
    https://blog.csdn.net/xutongbao/article/details/82983511 ↩︎

发布了11 篇原创文章 · 获赞 9 · 访问量 2469

猜你喜欢

转载自blog.csdn.net/weixin_43553694/article/details/93376489