返回 AiToEarn
useDocumentTitle.ts
根目录 / project / aitoearn-web / src / hooks / useDocumentTitle.ts
1 /**
2 * useDocumentTitle - 动态更新浏览器页面标题
3 * 功能:在客户端组件中动态设置 document.title
4 */
5 import { useEffect } from 'react'
6 import { useGetClientLng } from '@/hooks/useSystem'
7 import { getPageTitle } from '@/utils/title'
8
9 /**
10 * 动态更新浏览器页面标题
11 * @param title - 页面标题(为空时使用 defaultTitle)
12 * @param defaultTitle - 默认标题(title 为空时使用)
13 *
14 * @example
15 * ```tsx
16 * // 基本用法
17 * useDocumentTitle(task?.title, '新对话')
18 *
19 * // 仅在有标题时更新
20 * useDocumentTitle(taskDetail?.title)
21 * ```
22 */
23 export function useDocumentTitle(title: string | undefined | null, defaultTitle?: string) {
24 const lng = useGetClientLng()
25
26 useEffect(() => {
27 ;(async () => {
28 const displayTitle = title || defaultTitle
29 if (displayTitle) {
30 document.title = await getPageTitle(displayTitle, lng)
31 }
32 })()
33 }, [title, defaultTitle, lng])
34 }
35
35 lines TYPESCRIPT