React PureComponent

PureComponent

父组件

import React, { Component } from 'react'
import Home from './Home'
import About from './About'

export default class App extends Component {
  constructor(){
    super()
    this.state = {
      message: 'hello world',
      age: 18
    }
  }

  changeMessage(){
    this.setState({
      message: this.state.message + '!'
    })
  }

  changeAge(){
    this.setState({
      age: this.state.age + 1
    })
  }

  render() {
    console.log('App')
    return (
      <div>
        <button onClick={ ()=> this.changeMessage() }>修改信息</button>
        <button onClick={ ()=> this.changeAge() }>修改年龄</button>
        <h1>Home</h1>
        <Home message={ this.state.message }></Home>
        <hr />
        <h1>About</h1>
        <About age={ this.state.age }></About>
      </div>
    )
  }
}

子组件1

import React, { Component } from 'react'

export default class Home extends Component {
  render() {
    console.log('Home')
    return (
      <div>{this.props.message}</div>
    )
  }
}

子组件2

import React, { PureComponent } from 'react'

export default class About extends PureComponent {
  render() {
    console.log('About')
    return (
      <div>{this.props.age}</div>
    )
  }
}

PureComponent是用来性能优化的

在父组件中若修改age,则父组件和所有的子组件都会重新调用render函数

在父组件中若修改message,则父组件和子组件1会重新调用render函数,子组件2中的props和state都没有修改,所以不会重新调用render函数

PureComponent只会进行浅比较,浅比较就是只比较第一级,对于基本数据类型,只比较值;

对于引用数据类型值,直接比较地址是否相同,不管里面内容变不变,只要地址一样,就认为没变。

memo

memo和PureComponent是一样的,只不过Memo是应用在函数组件中

import React, { PureComponent } from 'react'

const About = memo(function(props){
    return (
        <div>{props.age}</div>
    )
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值