react中的纯组件pureComponent

本文介绍React中纯组件(PureComponent)的使用方法及其如何通过浅层对比优化组件的渲染性能,包括值类型与引用类型的对比原理,以及如何正确更新state以避免不必要的渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯组件的作用:内部自动在shouldComponentUpdate钩子函数中帮我们进行了比对,不需要我们手动来进行比对

使用方法:之前我们使用组件都是继承React.Component,而我们想要使用纯组件的话,只需要继承React.PureComponent即可。

  • 纯组件内部的对比是shallow compare(浅层对比)两种类型
  • 值类型:比较两个值是否相同
  • 引用类型:只比对对象引用地址是否相同

注:state或props中属性值为引用类型时,应该创建新数据,不要修改原数据

浅层对比的原理:

在父组件中使用PureComponent

import React from 'react'
import ReactDOM from 'react-dom'

/* 
  组件性能优化:
*/

// 生成随机数
class App extends React.PureComponent {
  state = {
    number: 0
  }
  handleClick = () => {
    this.setState(() => {
      return {
        number: Math.floor(Math.random() * 3)
      }
    })
  }

  render() {
    console.log('父组件中的render')
    return (
      <div>
        <h1>随机数:{this.state.number}</h1>
        <button onClick={this.handleClick}>重新生成</button>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

在子组件使用PureComponent

import React from 'react'
import ReactDOM from 'react-dom'

/* 
  组件性能优化:
*/

// 生成随机数
class App extends React.Component {
  state = {
    number: 0
  }

  handleClick = () => {
    this.setState(() => {
      return {
        number: Math.floor(Math.random() * 3)
      }
    })
  }

  render() {
    return (
      <div>
        <NumberBox number={this.state.number} />
        <button onClick={this.handleClick}>重新生成</button>
      </div>
    )
  }
}

class NumberBox extends React.PureComponent {
  render() {
    console.log('子组件中的render')
    return <h1>随机数:{this.props.number}</h1>
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值