React生命周期shouldComponentUpdate介绍及性能优化

在react开发中,经常要对数据state状态进行改变,但是这种方式每当setState的时候都会将所有的组件重新渲染一遍,这样就会有重复渲染render的问题,会造成不必要的性能开销
在这里插入图片描述


shouldComponentUpdate介绍
shouldComponentUpdate(nextProps, nextState)
  • nextProps: 表示下一个props
  • nextState: 表示下一个state的值

使用shouldComponentUpdate就是为了减少render不必要的渲染。返回布尔值,然后做Virtual DOM比较,并得出是否需要做真实DOM更新。

import React, { Component } from 'react'
class Title extends Component {
    shouldComponentUpdate(nextProps){
    	// 比较之前的title和传来的title是否相同,如果相同,不重新render; 如果不相同,重新render
        return nextProps.title!==this.props.title
    }
    render() {
        console.log("我是title组件")
        return (
            <div>
                标题:{this.props.title}
            </div>
        )
    }
}

class Count extends Component {
    render() {
        console.log("我是条数组件")
        return (
            <div>
                条数:{this.props.count}
            </div>
        )
    }
}

// Purememo整个组件会重新渲染,如果不使用shouldComponentUpdate那么Title,Count会一直渲染,但是使用shouldComponentUpdate后Title则不会发生渲染。
export default class Purememo extends Component {
    constructor(props){
        super(props)
        this.state={
            title:'shouldComponentUpdate使用',
            count:0
        }
    }
    componentDidMount(){
        setInterval(()=>{
            this.setState({
                count:this.state.count+1
            })
        },1000)
    }
    render() {
        return (
            <div>
                <Title title={this.state.title}></Title>
                <Count count={this.state.count}></Count>
            </div>
        )
    }
}
  • 如果是进行引用类型的比较(就是对象的地址不变,但是对象里面的值会改变,就无法进行render了)
解决方法:

npm install immutable

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值