当前位置: 首页 > news >正文

useWhyDidYouUpdate详解

目录

API

Params

demo演示

源码 


useWhyDidYouUpdate是ahooks库中的一个hook函数,用于帮助开发者排查是哪个属性改变导致了组件的 rerender。

API

type IProps = Record<string, any>;useWhyDidYouUpdate(componentName: string, props: IProps): void;

Params

参数说明类型默认值
componentName必填,观测组件的名称(ps:只是一个代号,自己能分别清楚即可)string-
props必填,需要观测的数据(当前组件 state 或者传入的 props 等可能导致 rerender 的数据)object-

demo演示

import { useState } from 'react'
import { useWhyDidYouUpdate } from 'ahooks';function Counter(props) {useWhyDidYouUpdate('Counter', props);return <><div><span>{props.title}:</span><span>{props.count}</span></div></>
}function App() {const [count, setCount] = useState(0)return (<><button onClick={() => setCount(count + 1)}>+1</button><Counter title={'计数显示'} count={count}  /></>)
}export default App

源码 

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的所有keylet keys = Object.keys({ ...oldPropsRef.current, ...props });// 改变信息对象let changeMessageObj: IProps = {};keys.forEach((key) => {// 对比新旧props是否改变,改变及记录到changeMessageObjif (!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);}// 更新refoldPropsRef.current = props;}});
};

http://www.lryc.cn/news/511849.html

相关文章:

  • c++入门——c++输入cin和输出cout的简单使用
  • Spring Cloud LoadBalancer (负载均衡)
  • 微服务-1 认识微服务
  • 基于51单片机的交通灯带拐弯proteus仿真
  • 1229java面经
  • MySQL中查看表结构
  • python利用selenium实现大麦网抢票
  • FME教程:一键批量调换图斑X、Y坐标,解决因为坐标弄反了,导致GIS弹窗提示“范围不一致”警告问题
  • OpenCV-Python实战(4)——图像处理基础知识
  • 音视频入门基础:MPEG2-PS专题(1)——MPEG2-PS官方文档下载
  • Qt自定义步骤引导按钮
  • 贝叶斯神经网络(Bayesian Neural Network)
  • Direct Preference Optimization: Your Language Model is Secretly a Reward Model
  • 如何通过 Kafka 将数据导入 Elasticsearch
  • 嵌入式系统 第十二讲 块设备和驱动程序设计
  • 攻防世界web第六题upload
  • 人工智能-Python网络编程-HTTP
  • 探索仓颉编程语言:功能、实战与展望
  • Unity-Editor扩展显示文件夹大小修复版 FileCapacity.cs
  • BLE core 内容整理解释
  • Linux CPU调度算法
  • Linux套接字通信学习
  • mybatis-plus 用法总结
  • 小程序配置文件 —— 14 全局配置 - tabbar配置
  • Redis-十大数据类型
  • linux系统编程(七)管道和FIFO
  • 【vLLM大模型TPS测试三部曲】
  • Elasticsearch:使用 Ollama 和 Go 开发 RAG 应用程序
  • Windows平台ROBOT安装
  • 【动态规划篇】穿越算法迷雾:约瑟夫环问题的奇幻密码