react生命周期

记录react生命周期

相比vue,react的生命周期更让我觉得更容易懂。。。

 创建时(挂载阶段)

组件创建时。执行顺序为: constructor() ---> render() --->componentDidMount

上示例理解: 

class Parent extends React.Component {
  constructor(props) {
    super(props)
    console.warn('生命周期钩子函数: constructor')
  }
  componentDidMount() {
     console.warn('生命周期钩子函数: componentDidMount')
  }
  render() {
    console.warn('生命周期钩子函数: render')
    return (
      <div>
        <h1>打豆豆</h1>
      </div>
    )
  }
}
ReactDOM.render(<Parent></Parent>,document.getElementById('app'))

更新时(更新阶段)

执行时机:setState() 、接收到新的props 、forceUpdate()

执行顺序: render() ---> componentDidUpdate()

 

卸载时(卸载阶段)

执行时机:组件从页面消失

 

class Parent extends React.Component {
  constructor(props) {
    super(props)
    console.warn('生命周期钩子函数: constructor')
    this.state = {
      count: 0
    }
  }
  clickChange = () => {
    this.setState({
      count: this.state.count +1
    })
  }
  render() {
    console.warn('生命周期钩子函数: render')
    return (
      <div>
        {this.state.count > 3 ? (<p>豆豆被打死了</p>) : (<Child count={this.state.count}/>)}
        {/* {<Child count={this.state.count}></Child>} */}
        <button onClick={this.clickChange}>+1</button>
      </div>
    )
  }
}
class Child extends React.Component {
  render() {
    return (
      <div>
        <h1 id="title">打豆豆:{this.props.count}</h1>
      </div>
    )
  }
  componentDidMount() {
    this.timerId = setInterval(() => {
      console.log('定时器正在执行')
    },500)
  }
  componentDidUpdate(preProps) {
    console.warn('生命周期钩子函数: componentDidUpdate')
    const testTitle = document.getElementById('title')
    console.log(testTitle.innerHTML)
    console.log(preProps,this.props)
    if (preProps.count !== this.props.count) {
      this.setState({})
    }
  }
  componentWillUnmount() {
    console.warn('生命周期钩子函数:componentWillUnmount')
    clearInterval(this.timerId)
  }
}

ReactDOM.render(<Parent></Parent>,document.getElementById('app'))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值