react学习每天一个hooks useWhyDidYouUpdate
作者:jimmy_fx
这篇文章主要为大家介绍了react学习每天一个hooks useWhyDidYouUpdate使用示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
先讲点废话
这个hooks我记忆很深,因为当时有一次面试的时候,叫我手写实现这个自定义hooks,哈哈,所以这个系列的第一个hooks 就准备是它了。
来看看效果
当我们的组件变得复杂的时候,你是不是想知道到底什么,导致了组件的渲染,或者值的变化是什么,这个hooks 就能解决你的问题。

hooks源码来了
type IProps = Record<string, unknown>;
/**
* 什么导致了页面render自定义hooks
*
* @param componentName 观测组件的名称
* @param props 需要观测的数据(当前组件 state 或者传入的 props 等可能导致 rerender 的数据)
*/
const useWhyDidYouUpdate = (componentName: any, props: any) => {
// 创建一个ref对象
let oldPropsRef = useRef<IProps>({});
useEffect(() => {
if (oldPropsRef.current) {
// 遍历新旧props的所有key
let keys = Object.keys({ ...oldPropsRef.current, ...props });
// 改变信息对象
let changeMessageObj: IProps = {};
keys.forEach((key) => {
// 对比新旧props是否改变,改变及记录到changeMessageObj
if (!Object.is(oldPropsRef.current[key], props[key])) {
changeMessageObj[key] = {
from: oldPropsRef?.current[key],
to: props[key],
};
}
});
// 是否存在改变信息,存在及打印
if (Object.keys(changeMessageObj).length) {
console.log(componentName, changeMessageObj);
}
// 更新ref
oldPropsRef.current = props;
}
});
};demo完整源码
import React, { useState, useRef, useEffect } from 'react';
import { Button, Statistic } from 'antd';
type IProps = Record<string, unknown>;
/**
* 什么导致了页面render自定义hooks
*
* @param componentName 观测组件的名称
* @param props 需要观测的数据(当前组件 state 或者传入的 props 等可能导致 rerender 的数据)
*/
const useWhyDidYouUpdate = (componentName: any, props: any) => {
// 创建一个ref对象
let oldPropsRef = useRef<IProps>({});
useEffect(() => {
if (oldPropsRef.current) {
// 遍历新旧props的所有key
let keys = Object.keys({ ...oldPropsRef.current, ...props });
// 改变信息对象
let changeMessageObj: IProps = {};
keys.forEach((key) => {
// 对比新旧props是否改变,改变及记录到changeMessageObj
if (!Object.is(oldPropsRef.current[key], props[key])) {
changeMessageObj[key] = {
from: oldPropsRef?.current[key],
to: props[key],
};
}
});
// 是否存在改变信息,存在及打印
if (Object.keys(changeMessageObj).length) {
console.log(componentName, changeMessageObj);
}
// 更新ref
oldPropsRef.current = props;
}
});
};
// 演示demo
const Demo: React.FC<{ count: number }> = (props) => {
useWhyDidYouUpdate('useWhyDidYouUpdateComponent', { ...props });
return (
<>
<Statistic title="number:" value={props.count} />
</>
);
};
export default () => {
const [count, setCount] = useState(0);
return (
<div>
<Demo count={count} />
<div>
<Button
type="primary"
onClick={() => setCount((prevCount) => prevCount - 1)}
>
count -
</Button>
<Button
type="primary"
onClick={() => setCount((prevCount) => prevCount + 1)}
style={{ marginLeft: 8 }}
>
count +
</Button>
</div>
</div>
);
};以上就是react学习每天一个hooks useWhyDidYouUpdate的详细内容,更多关于react hooks useWhyDidYouUpdate的资料请关注脚本之家其它相关文章!
