React中shouldComponentUpdate的使用

本文探讨了React组件生命周期中的shouldComponentUpdate方法,如何通过纯组件(PureComponent)和function组件的React.memo实现组件更新优化,避免不必要的渲染。通过浅比较props和state,控制组件更新策略。

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

shouldComponentUpdate:而生命周期中有一个叫做shouldComponentUpdate的,从名字就可以看出来:组件是否应该更新,如果我们返回false的话,那么react是不会去进行diff流程,也不会去对比props,更不会去更新用户界面上的组件了。

我们平时可以通过继承PurComponent组件来达到一个简单的优化效果,继承了PurComponent之后会对props进行一层浅比较,在props没有改变的情况下不会去重新走diff更新流程。
而我们在使用function组件的时候也可以通过React.memo达到相同的效果。

//otherContent.js
export default class OtherContent extends PureComponent {
  render() {
    console.log("otherContent render")
    return (
      <>
        <div>other content</div>
      </>
    )
  }
}

1.在App.js中引入需要展示的组件

在这里插入图片描述
2.在子组件中定义方法,触发diff算法
在这里插入图片描述

import { Component } from 'react'

export default class ContextContent extends Component {
  constructor(...args) {
    super(...args)
    this.state = {
      num: 0
    }
  }
  fn() {
    this.setState({
      num: 1
    })
  }
  shouldComponentUpdate(nextProps, nextState) {
  //nextProps:表示下一个props
  //nextState:表示下一个state的值
    if (nextState.num !== this.state.num) {
      return true
    }
    return false
  }


  render() {

    console.log("Context render")

    return (
      <div>
        {this.state.num}
        <button onClick={this.fn.bind(this)}>点击</button>
      </div>)


  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值