【React】shouldComponentUpdate与React.PureComponent

UI=render(data),你负责提供data,React负责render
React的工作就是渲染,就是操作DOM,而且是很有智慧地操作DOM。
组件的stateprops变化时,React会比对这次虚拟DOM和上次虚拟DOM,然后根据二者的不同,来操作真实DOM。

shouldComponentUpdate
  • index.js
import React from 'react';
import ReactDOM from 'react-dom';
import CountDown from "./countDown.js";
ReactDOM.render(
    <CountDown initialCount={10}/>,
    document.querySelector('#root')
)
  • index.css
.btn,.count{
    margin-right:5px;
}
  • countDown.js
import React from "react";
import "./index.css";
class CountDown extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            count:props.initialCount
        }
        this.handleIncrement = () => {
            this.setState(currentState => ({
                count:currentState.count+1
            }))
        }
        this.handleDecrement = () => {
            this.setState(currentState => ({
                count:currentState.count-1
            }))
        }
        this.handleClick = () => {
            this.setState(currentState => ({
                count:currentState.count
            }))
        }
    }
    render(){
        console.log("enter render");
        return (
            <>
            <span className="count">{this.state.count}</span>
            <button className="btn" onClick={this.handleIncrement}>+</button>
            <button className="btn" onClick={this.handleDecrement}>-</button>
            <button className="btn" onClick={this.handleClick}>click me</button>
            </>
        )
        
    }
}
export default CountDown; 

在这里插入图片描述
点击+时,state.count加1,进入render重新渲染;
点击-时,state.count减1,进入render重新渲染;
点击click me时,state.count没变,为啥还要进入render重新渲染?

这个锅 shouldComponentUpdate 得背!
因为handleClick里调用setState()时并没有立即更新state,而是先问了shouldComponentUpdateshouldComponentUpdate给了肯定的答复后,才往下走继续更新state、重新render的。
React里 shouldComponentUpdate的默认实现是返回true

    shouldComponentUpdate(nextProps,nextState){
        return true
    }

那么,我们就会想了,是不是shouldComponentUpdate给了否定的答案,后面的状态更新、组件渲染就会停止?是的,的确如此。
如果shouldComponentUpdate始终返回false,不论点哪个按钮,计数器数值都不会改变。

    shouldComponentUpdate(nextProps,nextState){
        return false
    }

当然,我们肯定不会这么做。我们只是希望点击+时计数器加1,点击-计数器减1,点击click me时,计数器值不变且不浪费时间重新渲染。
所以,添加的shouldComponentUpdate就像下面这样:

    shouldComponentUpdate(nextProps,nextState){
    	// console.log('this.state.count:',this.state.count,'nextState.count:',nextState.count);
        if(nextState.count === this.state.count) return false;
        return false
    }

shouldComponentUpdate接受两个参数:nextPropsnextState
nextState, 本次的statethis.state,上次的state
nextProps,本次的propsthis.props,上次的props
在这里插入图片描述

React.PureComponent

如果比较的只是字符串、数值、布尔值等基本数据类型,React.PureComponent也是个不错的方案,这时我们就可以偷懒不写shouldComponentUpdate了。

import React from "react";
import "./index.css";
// class CountDown extends React.Component{
class CountDown extends React.PureComponent{    
    constructor(props){
        super(props);
        this.state = {
            count:props.initialCount
        }
        this.handleIncrement = () => {
            this.setState(currentState => ({
                count:currentState.count+1
            }))
        }
        this.handleDecrement = () => {
            this.setState(currentState => ({
                count:currentState.count-1
            }))
        }
        this.handleClick = () => {
            this.setState(currentState => ({
                count:currentState.count
            }))
        }
    }
    render(){
        return (
            <>
            <span className="count">{this.state.count}</span>
            <button className="btn" onClick={this.handleIncrement}>+</button>
            <button className="btn" onClick={this.handleDecrement}>-</button>
            <button className="btn" onClick={this.handleClick}>click me</button>
            </>
        )
        
    }
}
export default CountDown; 

当然,应对 数组、对象等引用类型时,React.PureComponent无能为力。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值