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

}

结语

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

相关推荐
IvanCodes1 小时前
Python 数据处理(十三):JSON、CSV 与数据序列化
开发语言·python
Setsuna_F_Seiei2 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
aramae3 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
Rain的Java大神之路4 小时前
如何快速上传10G文件
java·spring boot·redis·后端·mysql·spring cloud·面试
百万蹄蹄向前冲4 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙4 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
大海星辰7985 小时前
一次对账SQL“灵异事件”排查:NOT IN返回空集的坑
mysql
linux_cfan5 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
狗狗狗狗狗乐啊5 小时前
搭一个 AI 对话工作台 AChat:从 0 到可用的完整记录(一)
python·react.js·ai编程
qq_2518364575 小时前
springboot vue3 开发实现 拼豆管理系统
java·开发语言·ai编程