重温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>
    )
  }

}

结语

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

相关推荐
Setsuna_F_Seiei32 分钟前
前端的 AI 学习之路 01 之 Agent API 调用 - 和 Agent 的基础对话
前端·人工智能·ai编程
覆东流34 分钟前
7.Java数组
java·开发语言·后端
码行山野赴时序归途1 小时前
三道经典数组题:从暴力到最优的算法思维
c语言·开发语言·数据结构·算法·leetcode
程序员小八7771 小时前
MySQL 事务:一文把 ACID、隔离级别、MVCC、锁全串起来
数据库·mysql
threerocks1 小时前
AI 原生软件开发生命周期手册 - 如何借助 AI,逐阶段改造软件开发生命周期
前端·javascript·后端
lzhdim1 小时前
提高 SQL 语句执行速度的方法
java·开发语言·数据库·sql·oracle
JavaPub-rodert1 小时前
王仕宇在 Go Context 如何解决协程泄漏与超时控制
开发语言·后端·golang·iphone·javapub·王仕宇
徐小夕1 小时前
3分钟从想法到Agent上线:我们开源了一款AI可视化工作流“IDE”
前端·算法·github
ly76893 小时前
JavaScript 从入门到进阶:核心语法、异步编程与工程化实践
开发语言·javascript·ecmascript
落魄大学生之流水线上谋生计3 小时前
Java锁全面指南:从基础概念到企业级应用
java·开发语言