useDebugValue

useDebugValue 是一个 React Hook,它可以让你在 React 开发者工具 中为自定义 Hook 添加标签。

useDebugValue(value, format?)

参考

🌐 Reference

useDebugValue(value, format?)

在你的 自定义 Hook 的顶层调用 useDebugValue 以显示可读的调试值:

🌐 Call useDebugValue at the top level of your custom Hook to display a readable debug value:

import { useDebugValue } from 'react';

function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}

查看更多示例。

参数

🌐 Parameters

  • value:你想在 React 开发工具中显示的值。它可以是任何类型。
  • 可选 format:一个格式化函数。当组件被检查时,React DevTools 会使用 value 作为参数调用该格式化函数,然后显示返回的格式化值(可以是任意类型)。如果你不指定格式化函数,将直接显示原始的 value

返回

🌐 Returns

useDebugValue 不返回任何值。

用法

🌐 Usage

为自定义钩子添加标签

🌐 Adding a label to a custom Hook

在你的 自定义 Hook 的顶层调用 useDebugValue,以显示一个可读的 调试值 ,用于 React DevTools

import { useDebugValue } from 'react';

function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}

这会在你检查它们时给调用 useOnlineStatus 的组件一个像 OnlineStatus: "Online" 的标签:

🌐 This gives components calling useOnlineStatus a label like OnlineStatus: "Online" when you inspect them:

A screenshot of React DevTools showing the debug value

如果没有 useDebugValue 调用,只有底层数据(在本例中为 true)会被显示。

🌐 Without the useDebugValue call, only the underlying data (in this example, true) would be displayed.

import { useSyncExternalStore, useDebugValue } from 'react';

export function useOnlineStatus() {
  const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
  useDebugValue(isOnline ? 'Online' : 'Offline');
  return isOnline;
}

function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

注意

不要在每个自定义 Hook 中添加调试值。它对属于共享库且具有复杂内部数据结构且难以检查的自定义 Hook 最有价值。

🌐 Don’t add debug values to every custom Hook. It’s most valuable for custom Hooks that are part of shared libraries and that have a complex internal data structure that’s difficult to inspect.


延迟调试值的格式化

🌐 Deferring formatting of a debug value

你也可以将一个格式化函数作为第二个参数传递给 useDebugValue

🌐 You can also pass a formatting function as the second argument to useDebugValue:

useDebugValue(date, date => date.toDateString());

你的格式化函数将接收 调试值 作为参数,并应返回一个 格式化显示值。当你的组件被检查时,React DevTools 将调用此函数并显示其结果。

这让你可以避免在组件实际被检查之前执行可能很昂贵的格式化逻辑。例如,如果 date 是一个日期值,这可以避免在每次渲染时对它调用 toDateString()

🌐 This lets you avoid running potentially expensive formatting logic unless the component is actually inspected. For example, if date is a Date value, this avoids calling toDateString() on it for every render.