React 学习笔记 17(useShouldComponentUpdate)

封装hooks,实现通过比较状态来实现是否更新组件(原始react中是没有类似比较状态更新组件的)

import {useState,useRef} from "react"

function useShouldComponentUpdate(initialValue, shouldUpdate) {
    // 满足条件后通过调用 setState 方法更新组件
    const [, setState] = useState(initialValue)
    // 自定义(状态)
    const ref = useRef(initialValue)
    //自定义设置状态的方法
    const renderUpdate = updateFunction => {
        // 判断 updateFuntion 类型,如果不是函数就报错
        if(!updateFunction instanceof Function) {
            throw new Error("updateFunction 必须为函数类型")
        }
        // 获取最新的状态
        const newValue = updateFunction(ref.current)
        // 根据条件决定是否更新组件
        if(shouldUpdate(ref.current,newValue)) {
            setState(newValue)
        }
        // 更新自定义状态
        ref.current = newValue
    }
    return [ref.current, renderUpdate]
}

// 使用
function App(){
    const [count, setCount] = useShouldComponentUpdate(0,(prev,next) => prev !== next)
return {
    <div>
        <p>{count}</p>
        <button onClick={()=> setCount(prev => prev + 1 )}>增加</button>
    </div>
    }
    
}

通过自定义hooks,实现性能的优化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值