posts - 59,comments - 0,views - 34881

1.第一次创建组件渲染的时候执行的钩子函数:

  1. 按钮触发的时候会执行的钩子函数:

点击查看代码
import React, { Component } from 'react'
// 生命周期的执行顺序与你代码写的顺序无关
class ChildrenItem extends Component {
  UNSAFE_componentWillMount() {
    console.log('生命周期---子组件UNSAFE_componentWillMount------只会执行一次')
  }
  componentDidMount() {
    console.log('生命周期---子组件componentDidMount------只会执行一次')
  }
  // 应该更新这个组件吗?性能组件
  // 第一个入参最新的props 第二个入参是最新的state
  shouldComponentUpdate(nextprops, nextstate) {
    console.log('子组件最新的属性nextprops', nextprops)
    console.log('子组件最新的状态nextstate', nextstate)
    console.log('生命周期---子组件的shouldComponentUpdate')
    return true
  }
  UNSAFE_componentWillUpdate() {
    // 但是这个钩子函数被历史抛弃了,官方不建议你再使用哦
    console.log('生命周期---子组件UNSAFE_componentWillUpdate')
  }
  componentDidUpdate(oldprops, oldstate) {
    console.log('生命周期---子组件的componentDidUpdate')
    console.log('子组件老的属性oldprops', oldprops)
    console.log('子组件老的状态oldstate', oldstate)
  }
  UNSAFE_componentWillReceiveProps(nextprops){ 
    // 作用:可以最先拿到父组件传递过来的新的属性,进行axios或者相应逻辑的处理
    // 无论父组件是否更新自组件中的任何内容或者并没有传任何属性给子组件,
    // 只要父组件进行setState的重新渲染,这个钩子函数就会执行,
    // 但是父组件第一次初始化创建子组件渲染的时候,该钩子函数并不会执行
    console.log('写在孩子组件会更有意义,不建议在根组件中使用',nextprops)
    console.log('生命周期---UNSAFE_componentWillReceiveProps')
    this.setState({
      // 你可以将父组件的属性转化成子组件的状态哦
      title:nextprops.name
    })
  }
  state={
    title:'月亮'
  }
  render() {
    return <div>{this.state.title}</div>
  }
}
export default class lifeCycle extends Component {
  UNSAFE_componentWillMount() {
    console.log('生命周期---父组件UNSAFE_componentWillMount------只会执行一次')
  }
  componentDidMount() {
    console.log('生命周期---父组件componentDidMount------只会执行一次')
  }
  shouldComponentUpdate(nextprops, nextstate) {
    console.log('父组件最新的属性nextprops', nextprops)
    console.log('父组件最新的状态nextstate', nextstate)
    console.log('生命周期---父组件的shouldComponentUpdate')
    return true
  }
  UNSAFE_componentWillUpdate(oldprops, oldstate) {
    // 但是这个钩子函数被历史抛弃了,官方不建议你再使用哦
    console.log('生命周期---父组件UNSAFE_componentWillUpdate')
    console.log('父组件老的属性oldprops', oldprops)
    console.log('父组件老的状态oldstate', oldstate)
  }
  componentDidUpdate() {
    console.log('生命周期---父组件componentDidUpdate')
  }
  state = {
    name: '团团'
  }
  render() {
    return (
      <div>
        <button
          onClick={() => {
            this.setState({
              name: '只是有点圆'
            })
          }}
        >change名称</button>
        <ChildrenItem name={this.state.name}></ChildrenItem>
      </div>
    )
  }
}

posted on   好久不见-库克  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示