React生命周期

React生命周期,第1张

钩子 函数触发时机
constructor创建组件时,最先执行,初始化的时候只执行一次
render每次组件渲染都会触发(注意: 不能在里面调用setState() 会陷入死循环)
componentDidMount组件挂载(完成DOM渲染)后执行,初始化的时候执行一次
componentDidUpdate组件更新后(DOM渲染完毕)
componentWillUnmount组件卸载(从页面中消失)

注意:只有类组件才有生命周期

组件挂载完成渲染
class App extends Component {
  constructor() {
    super()
    console.log("1.constructor")
  }
  componentDidMount () {
    console.log("3.componentDidMount")
  }
  render () {

    console.log("2.render")
    return (
      
        生命周期测试
      
    )
  }
}

React 在 开发环境下会刻意执行两次渲染,以防止组件内有什么 side effect 引发 bug,提早预防。这里官方github上有做出解释: 

组件更新时的生命周期 
class App extends Component {
  state = {
    count: 0
  }
  UpdateData = () => {
    this.setState({
      count: this.state.count + 1
    })
  }
  componentDidUpdate () {
    //组件更新时触发
    console.log("componentDidUpdate")
  }
  render () {
    return (
      
        生命周期测试
        
      
    )
  }
}

组件卸载的生命周期 
class SonA extends Component {

  componentWillUnmount () {
    //组件被卸载时触发
    console.log("componentWillUnmount")
  }
  render () {
    return (
      
        组件卸载测试
      
    )
  }
}

class App extends Component {
  state = {
    count: 0,
    onoff: true
  }
  UpdateData = () => {
    this.setState({
      count: this.state.count + 1,
      onoff: !this.state.onoff
    })
  }
  render () {
    console.log("2.render")
    return (
      
        生命周期测试
        {this.state.onoff ?  : ""}
        
      
    )
  }
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1320747.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-11
下一篇2022-06-11

发表评论

登录后才能评论

评论列表(0条)

    保存