验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

react hooks useWhyDidYouUpdate源码分析

阅读:359 来源:乙速云 作者:代码code

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 (
    
             
         setCount((prevCount) => prevCount - 1)}         >           count -                   setCount((prevCount) => prevCount + 1)}           style={{ marginLeft: 8 }}         >           count +                
    
  ); };
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>