重温react-05(类组件生命周期和性能优化)

类组件的生命周期

javascript 复制代码
import React, { Component } from 'react'

export default class learnReact05 extends Component {
  state = {
    number: 1
  }
  render() {
    return (
      <div>{this.state.number}</div>
    )
  }
  // 一般将请求的方法,放在这个生命周期
  componentDidMount() {
    setInterval(() => {
      this.setState({
        number: this.state.number + 1
      })
    }, 1000)
  }

  // 更新阶段 =>组件卸载
  componentWillUnmount(){
    console.log('卸载');
  }
}

组件性能优化

06的代码

javascript 复制代码
import React, { Component } from 'react'
import LearnReact07 from './learnReact07'
export default class learnReact06 extends Component {
  state = {
    arr: ['组件1', '组件2', '组件3', '组件4'],
    number: 0
  }
  render() {
    return (
      <div>
        <input type="number" value={this.state.number} onChange={this.changeNumber} />
        <div>{this.state.number}</div>
        {
          this.state.arr.map((item, index) => {
            return <LearnReact07 key={index} item={item} index={index} changeMsg={this.changeMsg} />
          })
        }
      </div>
    )
  }

  changeMsg = (index) => {
    const arr = [...this.state.arr]
    arr[index] = '哈哈哈哈'
    this.setState({
      arr: arr
    })
  }
  changeNumber = (e) => {
    this.setState({
      number: e.target.value
    })
  }
}

07的代码

javascript 复制代码
import React, { Component } from 'react'

export default class learnReact07 extends Component {
  shouldComponentUpdate = (nextProps, nextState) => {
    return nextProps.item != this.props.item

  }
  render() {
    // console.log('子组件是否触发');
    return (
      <div>
        <h1>{this.props.item}</h1>
        <button onClick={() => {
          this.props.changeMsg(this.props.index)
        }}>点击我改变嗷</button>
      </div>
    )
  }

}

结语

到此类组件已经全部完成学习,通常类组件在工作中不是经常使用,接下来要开启函数组件的学习。不断的强化自己,让自己可以在前端领域不断提升自己。

相关推荐
答案answer几秒前
一些经典的3D编辑器开源项目
前端·开源·three.js
Hello.Reader8 分钟前
在 Flink Standalone 集群上运行 Flink CDC从下载到跑起一个 MySQL→Doris 同步任务
大数据·mysql·flink
闫有尽意无琼9 分钟前
银河麒麟v11 arm编译Qt creator8.0.2报错
开发语言·qt
2***d88510 分钟前
使用 MySQL 从 JSON 字符串提取数据
mysql·oracle·json
亿元程序员17 分钟前
Creator都快4.0了,怎么能没有这样的功能?
前端
小满、19 分钟前
MySQL :锁机制、InnoDB 架构与 MVCC 解析
数据库·mysql·innodb·mvcc·锁机制
q***649719 分钟前
SpringMVC 请求参数接收
前端·javascript·算法
小此方22 分钟前
从零开始手搓堆:核心操作实现 + 堆排序 + TopK 算法+ 向上调整 vs 向下调整建堆的时间复杂度严密证明!
开发语言·数据结构·算法
万少22 分钟前
流碧卡片 6 小时闪电开发 AI gemini-3-pro-preview ! 秒出小红书爆款图,免下载直接用
前端·后端·ai编程
悟能不能悟23 分钟前
<style scoped>vue中怎么引用css文件
css·vue.js