React生命周期函数

LifeCycleCom.jsx

import React, { Component } from 'react'

// 定义一个子组件
class SubCom extends Component {

  state = {
    msg: '这是初始数据'
  }

  // 该生命周期函数可以监听页面数据的变化
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    // 当父组件数据发生变化才会触发该生命周期函数的执行
    console.log('子-01-componentWillReceiveProps', nextProps, nextContext)
    // 可能在某些场景下 视图没有更新,此时 需要 this.setState
  }

  // 该声明周期函数必须要有返回值,而且返回一个布尔值,true表示数据更新视图也更新,如果是false,就会阻止视图更新
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    /*
      nextProps: 更新后的数据
      nextState: 初始数据

    */
    console.log('子-02-shouldComponentUpdate', nextProps, nextState, nextContext)
    return true
  }

  UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
    console.log('子-03-componentDidUpdate', nextProps, nextState, nextContext)
  }


  render() {

    console.log('子-04-render')
    
    const { list } = this.props

    return (
      <div className="sub-com">
        <h1>子组件</h1>
        <ul>
          {
            list.map((item, index) => {
              return <li key={index}>{item}</li>
            })
          }
        </ul>
      </div>
    )
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('子-05-componentDidUpdate', prevProps, prevState, snapshot)
  }

  componentWillUnmount() {
    console.log('子-06-componentWillUnmount')
  }
}

export default class LifeCycleCom extends Component {

  constructor(props) {
    super(props)

    this.state = {
      msg: '演示旧版本生命周期函数:',
      arr: ['vue', 'react', 'flutter']
    }

    console.log('父-01-contructor')
  }

  // 在这个阶段是可以请求数据,但是首页可能会出现白屏的现象,也有可能造成多次渲染等不确定的问题,而且在17.x版本中将要废弃该生命周期函数,所以不建议在componentWillMount这个阶段请求数据,可以在构造函数中请求数据
  UNSAFE_componentWillMount() {
    console.log('父-02-componentWillMount')
  }

  handleClick = (e) => {
    const { arr } = this.state
    arr.push(Math.random())
    this.setState({arr})
  }

  render() {
    console.log('父-03-render')
    const { msg, arr } = this.state
    return (
      <div>
        {
          msg && <h1>{msg}</h1>
        }

        <button onClick={this.handleClick}>改变状态</button>

        <SubCom list={arr} />
      </div>
    )
  }

  // 在这个阶段相当于window.onload,我们可以操作真实dom,
  // 在此阶段请求接口
  componentDidMount() {
    console.log('父-04-componentDidMount')
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值