react hooks useWhyDidYouUpdate源码分析
hooks源码来了
type IProps = Record;
/**
* 什么导致了页面render自定义hooks
*
* @param componentName 观测组件的名称
* @param props 需要观测的数据(当前组件 state 或者传入的 props 等可能导致 rerender 的数据)
*/
const useWhyDidYouUpdate = (componentName: any, props: any) => {
// 创建一个ref对象
let oldPropsRef = useRef({});
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;
/**
* 什么导致了页面render自定义hooks
*
* @param componentName 观测组件的名称
* @param props 需要观测的数据(当前组件 state 或者传入的 props 等可能导致 rerender 的数据)
*/
const useWhyDidYouUpdate = (componentName: any, props: any) => {
// 创建一个ref对象
let oldPropsRef = useRef({});
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 (
<>
>
);
};
export default () => {
const [count, setCount] = useState(0);
return (
);
};
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。