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

}

结语

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

相关推荐
qq_411262421 天前
短时间串口发送网络端怎么接收不到
开发语言·php
静谧空间1 天前
java登录验证码CaptchaConfig
java·开发语言
小高Baby@1 天前
session、cookie、Jwt-token
开发语言·后端·golang
咔咔一顿操作1 天前
轻量无依赖!autoviwe 页面自适应组件实战:从安装到源码深度解析
javascript·arcgis·npm·css3·html5
maplewen.1 天前
C++11 std::mutex
开发语言·c++
jiaguangqingpanda1 天前
Day37-20260205
java·开发语言
历程里程碑1 天前
21:重谈重定义理解一切皆“文件“及缓存区
linux·c语言·开发语言·数据结构·c++·算法·缓存
李少兄1 天前
MySQL 中为时间字段设置默认当前时间
android·数据库·mysql
weixin_433179331 天前
Python - 软件对象
开发语言·python
刘联其1 天前
.net也可以用Electron开发跨平台的桌面程序了
前端·javascript·electron