封装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,实现性能的优化