前言

现代前端工程中,状态管理是一条贯穿全部业务逻辑的暗河。用户的每次点击、每次输入、每次 API 请求的响应,最终都汇入状态层,再从状态层流向 UI 渲染。

状态管理的架构选择决定了代码的复杂度上限,也决定了多人协作时的认知负担。

企业智能知识库前端选择了 Zustand 作为唯一全局状态库,完全弃用 React Context API 做状态分发,不使用 Redux。这意味着:没有 Provider 嵌套地狱,没有 action/reducer 样板代码,组件通过 useXxxStore() 直接消费状态,store 本质上是一个 create((set, get) => (...)) 的工厂函数。

配合 persist 中间件实现浏览器持久化,ref + setInterval 实现智能草稿保存,fetch + ReadableStream 解析 SSE 流式响应,STOMP over SockJS 接收实时通知推送。

1. 从一个 AI 对话请求看状态流转全链路

以用户在 AI 助手页面发送一条消息为例,完整描述状态如何在各层之间流转:

用户在 AI 聊天页输入 "RAG 和 KAG 的区别?" 并点击发送
  → AIPage.tsx: onSend(message)
  → useAIStore.sendMessage("RAG 和 KAG 的区别?")
       │
       ├── 1. 乐观更新:本地创建 userMessage
       │     ├── selectedModel = "qwen"
       │     ├── ragEnabled = true, kagEnabled = true
       │     ├── userMessage = { id: Date.now(), role: 'user', content: '...' }
       │     └── set({ isLoading: true, isStreaming: true, currentResponse: '' })
       │
       ├── 2. 追加 userMessage 到 currentConversation.messages
       │     └── 如果 currentConversation 为空,创建本地占位对话(id='')
       │
       ├── 3. 调用 aiService.askStream()
       │     ├── 用 fetch() 而非 Axios(Axios 响应拦截器会吞掉 ReadableStream)
       │     ├── 手动设置 Authorization Header
       │     └── POST /ai/chat/stream
       │
       ├── 4. ReadableStream 解析 SSE 事件流:
       │     ├── event: message / data: "RAG 是检索增强..."
       │     │     └── onMessage(chunk) → useAIStore 累加 currentResponse += chunk
       │     │           └── 组件实时渲染 AI 逐字打字效果
       │     │
       │     ├── event: done / data: { conversationId: 456, messageId: 789 }
       │     │     └── onDone(result) → 使用后端返回的权威 conversationId
       │     │           └── 创建 assistantMessage,追加到 currentConversation
       │     │           └── 如果是新对话,同步加入侧边栏 conversations 列表
       │     │
       │     └── event: error / data: "模型服务超时"
       │           └── onError(errMsg) → throw → catch → 恢复状态
       │
       └── 5. 流式完成,最终 set():
             ├── currentConversation: { id: 456, messages: [userMsg, asstMsg] }
             ├── conversations: [updatedConv, ...]  ← 同步侧边栏
             ├── isLoading: false
             ├── isStreaming: false
             └── currentResponse: ''  ← 清空流式缓冲
关键洞察:整个 AI 对话流程只涉及 一个 Store(useAIStore),只调用 **一个 Action**(sendMessage)。用户的 userMessage 是**乐观创建**的(不等待后端),流式文本通过 currentResponse 字段累加渲染,后端的 conversationId 通过 SSE done 事件回调获取。这就是 Zustand "扁平化状态管理"的典型模式 —— 不需要 dispatch,不需要 middleware,set() 就是全部。

2. 状态管理架构全景图

2.1 分层架构

┌─────────────────────────────────────────────────────────────────────┐
│                        React 组件层 (Components)                      │
│   DocumentsPage  AIPage  CreateDocumentPage  DraftsPage  AdminPage  │
│        │             │              │               │          │      │
│        ▼             ▼              ▼               ▼          ▼      │
│  useDocumentStore  useAIStore  useAutoSave()  useAuthStore  ...     │
└─────────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                   Zustand Store 层 (12 Stores)                       │
│                                                                      │
│  ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────────┐        │
│  │ auth     │ │ document │ │ ai         │ │ notification   │        │
│  │ (persist)│ │          │ │            │ │                │        │
│  └──────────┘ └──────────┘ └────────────┘ └───────────────┘        │
│  ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────────┐        │
│  │ app      │ │ category │ │ favorite   │ │ user           │        │
│  └──────────┘ └──────────┘ └────────────┘ └───────────────┘        │
│  ┌──────────┐ ┌──────────┐ ┌────────────┐ ┌───────────────┐        │
│  │ team     │ │ version  │ │ ai-writing │ │ file-management│        │
│  └──────────┘ └──────────┘ └────────────┘ └───────────────┘        │
└─────────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                     Service 层 (API 调用)                             │
│                                                                      │
│  ┌─────────────────┐  ┌──────────────────┐  ┌──────────────────┐   │
│  │ Axios Instance  │  │ fetch() + SSE    │  │ STOMP/SockJS     │   │
│  │ (request.ts)    │  │ (ai.service.ts)  │  │ (ws.service.ts)  │   │
│  │                 │  │                  │  │                  │   │
│  │ • 请求拦截器    │  │ • ReadableStream │  │ • /user/queue/   │   │
│  │ • 响应拦截器    │  │ • SSE 事件解析   │  │ • /topic/        │   │
│  │ • Token 刷新    │  │ • 手动 Auth 头   │  │ • 自动重连       │   │
│  │ • 数据脱壳      │  │                  │  │ • 心跳保活       │   │
│  └─────────────────┘  └──────────────────┘  └──────────────────┘   │
└─────────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                     浏览器存储层 (Browser Storage)                     │
│                                                                      │
│  ┌─────────────┐  ┌──────────────┐  ┌───────────────────────────┐  │
│  │ Cookie      │  │ localStorage │  │ Zustand persist middleware │  │
│  │             │  │              │  │                           │  │
│  │ access_token│  │ kb_draft_*   │  │ auth-storage → auth.store │  │
│  │ refresh_tok │  │ user_info    │  │                           │  │
│  │ (7天过期)   │  │ expires_at   │  │                           │  │
│  └─────────────┘  └──────────────┘  └───────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────┘

2.2 关键技术选型对比

维度本系统选择业界常见替代选择理由
全局状态库Zustand 4.5Redux Toolkit, MobX, Jotai无 Provider、无 boilerplate、天然支持 TypeScript
状态持久化Zustand persist 中间件Redux Persist与 Zustand 无缝集成,partialize 精确控制序列化字段
组件级状态useState + useRefuseReducer字段少且无复杂状态机,useState 足够;useRef 用于避免计时器闭包陷阱
SSE 流式原生 fetch + ReadableStreamEventSource, AxiosEventSource 不支持 POST 和自定义 Header;Axios 响应拦截器会破坏流
WebSocketSTOMP over SockJS原生 WebSocket, Socket.IO与 Spring STOMP 天然对接;SockJS 兼容不支持 WebSocket 的浏览器
无 React ContextZustand 直接消费createContext + useContextContext 每次值变化触发全部消费者重渲染;Zustand 支持 selector 精确订阅

3. Zustand Store 全景:12 个 Store 的职责与边界

项目中共有 12 个 Zustand Store,统一通过 src/stores/index.ts 桶文件导出。每个 Store 的文件结构与职责如下:

3.1 认证 Store(auth.store.ts)—— 唯一使用 persist 的生产 Store

// src/stores/auth.store.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<void>;
  clearAuth: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      isLoading: false,

      login: async (username, password) => {
        set({ isLoading: true });
        const response = await authService.login({ username, password });
        tokenStorage.saveToken(response);          // → Cookie + localStorage
        set({ user: normalizeLoginUser(response.userInfo),
              token: response.accessToken,
              isAuthenticated: true,
              isLoading: false });
      },

      checkAuth: async () => {
        const token = tokenStorage.getAccessToken()  // Cookie 优先
                   || get().token
                   || localStorage.getItem('token');
        if (!token) { set({ isAuthenticated: false }); return; }
        const currentUser = await authService.getCurrentUser();
        set({ user, isAuthenticated: true });
      },

      clearAuth: () => {
        tokenStorage.clearToken();
        set({ user: null, token: null, isAuthenticated: false });
        localStorage.removeItem('auth-storage');
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({          // 只持久化这三个字段
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

核心特性:

  • persist 中间件将 { user, token, isAuthenticated } 序列化到 localStorage key auth-storage
  • partialize 过滤掉 isLoading 等瞬态字段,避免刷新页面后显示 loading
  • login() 调用 tokenStorage.saveToken() 双写到 Cookie 和 localStorage
  • checkAuth() 按 Cookie → localStorage → Store 三级 fallback 读取 token
  • clearAuth() 清除三层存储,确保登录态彻底销毁

3.2 文档 Store(document.store.ts)—— 最复杂的 CRUD Store

// src/stores/document.store.ts
interface DocumentState {
  documents: Document[];
  currentDocument: Document | null;
  prevDocument: Document | null;          // 上一篇导航
  nextDocument: Document | null;          // 下一篇导航
  isLoading: boolean;
  total: number;
  currentPage: number;
  pageSize: number;                       // 默认 12
  filter: DocumentFilter;
  fetchingDocumentId: string | null;      // 防重复请求
}

关键设计决策:

防重复请求 —— 两个独立的锁:

// 列表请求:isLoading 锁
fetchDocuments: async (filter) => {
  if (get().isLoading) return;  // 防止并发列表请求
  // ...
}

// 详情请求:fetchingDocumentId 锁
fetchDocument: async (id) => {
  if (get().fetchingDocumentId === id) return;  // 防止同一文档并发请求
  set({ isLoading: true, fetchingDocumentId: id });
  // ...
}

乐观更新 —— likeDocument() 的三阶段模式:

likeDocument: async (id) => {
  // 1. 调用后端 API(like / unlike)
  await documentService.likeDocument(id);

  // 2. 乐观切换:立即翻转 isLiked 状态给用户即时反馈
  set((state) => ({
    documents: state.documents.map(doc =>
      doc.id === id ? { ...doc, isLiked: !doc.isLiked } : doc
    ),
    currentDocument: state.currentDocument?.id === id
      ? { ...state.currentDocument, isLiked: !state.currentDocument.isLiked }
      : state.currentDocument,
  }));

  // 3. 从后端重新拉取文档详情,获取真实的 likeCount
  try {
    const document = await documentService.getDocument(id);
    set((state) => ({
      documents: state.documents.map(doc =>
        doc.id === id ? { ...doc, likeCount: document.likeCount, isLiked: document.isLiked } : doc
      ),
    }));
  } catch {
    // 后端拉取失败时保留乐观更新的 isLiked 状态
  }
}

上一篇/下一篇导航 —— 获取文档详情后自动拉取相邻文档:

fetchDocument: async (id) => {
  const document = await documentService.getDocument(id);
  set({ currentDocument: document, isLoading: false });
  get().fetchAdjacentDocuments(id);  // 自动触发
}

Filter 智能更新 —— 只在真正变化时才触发:

setFilter: (filter) => {
  set((state) => {
    const hasChanged = Object.keys(filter).some(
      key => JSON.stringify(state.filter[key]) !== JSON.stringify(filter[key])
    );
    return hasChanged ? { filter: { ...state.filter, ...filter } } : {};
  });
}

3.3 AI Store(ai.store.ts)—— 流式状态管理的核心

// src/stores/ai.store.ts
interface AIState {
  conversations: AIConversation[];
  currentConversation: AIConversation | null;
  isLoading: boolean;
  isStreaming: boolean;
  currentResponse: string;            // SSE 实时文本缓冲区
  selectedModel: string;              // 默认 "qwen"
  availableModels: AIModelOption[];
  ragEnabled: boolean;
  kagEnabled: boolean;
}

sendMessage()** 的完整流程**(150+ 行业务逻辑):

1. 乐观创建 userMessage 并追加到 currentConversation
   ├── 无 active 对话 → 创建占位对话(id='',待后端 done 事件填充真实 ID)
   └── 有 active 对话 → 直接追加(兼容侧边栏选中的空消息对话)

2. 调用 aiService.askStream() 建立 SSE 连接
   ├── 仅在已有后端真实 ID 时才传 conversationId
   └── 占位空串不传,让后端自行创建

3. SSE 流式回调:
   ├── onMessage(chunk) → set({ currentResponse: state.currentResponse + chunk })
   ├── onDone({ conversationId, messageId, citations, graphContext })
   │     └── 捕获后端返回的权威 ID
   └── onError(errorMsg) → throw

4. 流式结束后构建 assistantMessage:
   ├── 新对话(之前无 ID)→ 同步加入侧边栏 conversations 列表
   └── 已有对话 → 更新 conversations 中对应项

对话合并策略 —— 刷新侧边栏时不覆盖本地消息:

fetchConversations: async () => {
  const apiConversations = await aiService.getConversations();
  const { currentConversation } = get();
  // 保留已有 messages 的对话数据,避免覆盖当前活跃对话
  const merged = apiConversations.map(api => {
    const existing = existingMap.get(String(api.id));
    return existing?.messages ? { ...api, messages: existing.messages } : api;
  });
  set({ conversations: merged });
}

模型列表获取的降级 —— API 失败时使用本地常量兜底:

fetchModels: async () => {
  try {
    const models = await aiService.getModels();
    set({ availableModels: models });
  } catch {
    // 降级:使用本地配置
    const { AI_CONFIG } = await import('@/constants');
    const fallbackModels = Object.values(AI_CONFIG.MODELS).map(m => ({
      key: m.key, displayName: m.displayName, description: m.description,
      isDefault: m.key === AI_CONFIG.DEFAULT_MODEL,
    }));
    set({ availableModels: fallbackModels });
  }
}

3.4 通知 Store(notification.store.ts)—— WebSocket 与 API 双通道

// src/stores/notification.store.ts
interface NotificationState {
  notifications: SystemNotification[];
  unreadCount: number;
  isLoading: boolean;

  // WebSocket 实时推送专用 action
  addNotification: (notification: SystemNotification) => void;
  incrementUnreadCount: (delta?: number) => void;
}

双通道数据来源:

  • API 通道:fetchNotifications() 页面加载时批量拉取(Promise.all 并发请求列表 + 未读数)
  • WebSocket 通道:addNotification() 在 MainLayout 中被 WebSocket 回调调用,实时插入列表头部

字段映射 —— 后端字段名与前端类型的转换:

function mapNotification(raw: any): SystemNotification {
  const documentId = String(raw?.relatedId ?? extractDocumentIdFromLink(raw?.link) ?? '');
  const target = resolveNotificationTarget({
    type: raw?.notificationType, link: raw?.link, documentId,
  });
  return {
    id: String(raw?.id ?? ''),
    type: raw?.notificationType,           // 后端 → 前端字段名映射
    title: raw?.title,
    content: raw?.content,
    link: target.url,                      // 根据类型解析跳转链接
    documentId: documentId || undefined,
    read: Boolean(raw?.isRead),            // isRead → read
  };
}

3.5 应用配置 Store(app.store.ts)—— 启动时加载全局开关

// src/stores/app.store.ts
interface AppState {
  systemName: string;           // "企业知识库"
  systemDescription: string;    // "智能企业知识管理平台"
  requireApproval: boolean;     // 发布是否需要审核
  enableAI: boolean;
  enableAIWriting: boolean;
  enableFullTextSearch: boolean;
  maxFileSize: number;          // 默认 100MB
  allowedFileTypes: string;     // PDF 始终包含(硬保证)
  loaded: boolean;              // 防止重复加载的标志位
}

启动流程 —— MainLayout 挂载时调用 fetchAppConfig():

MainLayout mount
  → useAppStore.fetchAppConfig()
    → loaded === true? → 跳过(幂等)
    → foundationService.config.getPublic()  // GET /foundation/config/public
    → 解析 CONFIG_MAP 和 BOOLEAN_CONFIG_MAP 映射
    → PDF 硬保证:typeSet.add('pdf')
    → set({ ...updates, loaded: true })
    → document.title = systemName + " | Enterprise Knowledge Base"
设计意图:loaded 标志位防止每次路由切换重新请求。失败时也设置 loaded: true(使用默认值),避免无限重试。

3.6 其他 Store 一览

Store文件核心状态关键特性
Categorycategory.store.tscategories, categoryTree平铺列表 + 树形结构双视图
Favoritefavorite.store.tsfavorites: Map<string, boolean>Map 结构实现 O(1) 收藏状态查询
Useruser.store.tsusers, currentUser, total用户管理 CRUD + 个人中心展示
Teamteam.store.tsteams, teamTree, selectedTeam团队管理 + 树形选择器
Versionversion.store.ts版本列表、当前版本、差异对比文档版本回滚、快照创建
AI Writingai-writing.store.tsgeneratedContent, tokens, wordCount流式写作 + 模板管理
File Mgmtfile-management.store.ts文件列表、上传状态大文件分片上传 + 乐观更新
Foundationfoundation.store.ts通知、配置、日志、字典Legacy Store,多数方法为 TODO 占位

4. 持久化策略:persist 中间件与双写 Cookie + LocalStorage

4.1 持久化架构

┌─────────────────────────────────────────────────────────────┐
│                    Zustand persist 中间件                      │
│                                                               │
│  auth-storage → { user, token, isAuthenticated }             │
│  监听 localStorage 变化,自动 rehydrate                       │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                  tokenStorage (单例)                          │
│                                                               │
│  Cookie (主要)          localStorage (备用)                   │
│  ┌─────────────────┐   ┌──────────────────┐                  │
│  │ access_token    │   │ access_token     │                  │
│  │ refresh_token   │   │ refresh_token    │                  │
│  │ path: /         │   │ token_type       │                  │
│  │ sameSite: lax   │   │ expires_at       │                  │
│  │ expires: 7天    │   │ user_info (JSON) │                  │
│  └─────────────────┘   └──────────────────┘                  │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                  draftStorage (工具对象)                       │
│                                                               │
│  kb_draft_{docId} → DraftData (有 ID 的草稿)                 │
│  kb_draft_new     → DraftData (新建文档的草稿)               │
└─────────────────────────────────────────────────────────────┘

4.2 Token 双写策略

// src/utils/token-storage.ts
class TokenStorageService {
  saveToken(loginResponse: LoginResponse): void {
    // 1. localStorage 备用
    localStorage.setItem('access_token', accessToken);
    localStorage.setItem('refresh_token', refreshToken);
    localStorage.setItem('expires_at', String(Date.now() + expiresIn * 1000));
    localStorage.setItem('user_info', JSON.stringify(userInfo));

    // 2. Cookie 主要存储
    cookieManager.set('access_token', accessToken, { expires: expiresIn/86400, path: '/', sameSite: 'lax' });
    cookieManager.set('refresh_token', refreshToken, { expires: expiresIn/86400, path: '/', sameSite: 'lax' });
  }

  getAccessToken(): string | null {
    return cookieManager.get('access_token')    // Cookie 优先
        || localStorage.getItem('access_token'); // localStorage 兜底
  }
}
为什么双写? Cookie 用于 HTTP 请求自动携带(如果决定使用 Cookie 模式),localStorage 用于前端业务逻辑(如判断登录状态、获取用户信息)。getAccessToken() 的 Cookie 优先策略确保即使 localStorage 被手动清理,Cookie 中的 token 仍然可用。

4.3 Cookie 管理器

// src/utils/cookie.ts
class CookieManager {
  defaultOptions = { expires: 7, path: '/', sameSite: 'lax' };

  set(key: string, value: string, options?: Partial<CookieOptions>): void
  get(key: string): string | null
  remove(key: string): void
  has(key: string): boolean
  getAll(): Record<string, string>
  clearAll(): void
}

5. 自定义 Hooks:草稿保存、防抖、分页

5.1 useAutoSave —— 最复杂的 Hook

useAutoSave 是前端最核心的业务 Hook,管理文档编辑过程中的自动保存、草稿恢复、变化检测。

// src/hooks/useAutoSave.ts
export type SaveStatus = 'idle' | 'saving' | 'saved' | 'error' | 'unsaved';

interface UseAutoSaveOptions {
  documentId?: string;         // 现有文档 ID(编辑模式)
  formData: AutoSaveFormData;  // 表单数据(title, content, summary, tags 等)
  enabled?: boolean;           // 默认 EDITOR_CONFIG.enableAutoSave
  interval?: number;           // 默认 AUTO_SAVE.INTERVAL = 10000ms
  onDocumentCreated?: (id: string) => void;  // 首次自动保存成功回调
}

interface UseAutoSaveReturn {
  saveStatus: SaveStatus;
  lastSavedAt: Date | null;
  currentDocId: string | undefined;    // 首次自动保存后获得的后端 ID
  hasRecoveryDraft: boolean;
  recoveryDraft: DraftData | null;
  isRecoveryDialogOpen: boolean;
  acceptRecovery: () => DraftData | null;
  dismissRecovery: () => void;
  clearDraft: () => void;
  performSave: () => Promise<void>;
}

内部 Ref 架构 —— 避免定时器闭包陷阱:

const formDataRef = useRef(formData);         // 始终指向最新 formData
const currentDocIdRef = useRef(currentDocId); // 始终指向最新 docId
const isSavingRef = useRef(false);           // 防止并发保存
const hasChangesRef = useRef(false);         // 脏标记
const saveToBackendRef = useRef<() => Promise<void>>(async () => {}); // 避免重置定时器

变化检测 —— 序列化比较:

const serialized = JSON.stringify(formData);
const prevSerialized = useRef(serialized);

useEffect(() => {
  if (serialized !== prevSerialized.current) {
    prevSerialized.current = serialized;
    hasChangesRef.current = true;
    setSaveStatus('unsaved');
  }
}, [serialized]);

周期保存 —— setInterval 驱动:

useEffect(() => {
  if (!enabled) return;
  const timer = setInterval(() => {
    if (hasChangesRef.current && !isSavingRef.current) {
      saveToBackendRef.current();   // 通过 ref 调用,避免闭包过期
    }
  }, interval);  // 默认 10 秒
  return () => clearInterval(timer);
}, [enabled, interval]);

保存到后端 —— 带 localStorage 兜底:

const saveToBackend = useCallback(async () => {
  if (isSavingRef.current) return;
  isSavingRef.current = true;
  setSaveStatus('saving');

  try {
    const payload = { id: currentDocIdRef.current || undefined, ...formData };
    const cleanPayload = Object.fromEntries(
      Object.entries(payload).filter(([_, v]) => v !== undefined && v !== 'undefined')
    );
    const result = await documentService.autoSaveDocument(cleanPayload);
    const docId = typeof result === 'string' ? result : String(result?.id);

    // 首次自动保存:设置 ID 并通知父组件
    if (!currentDocIdRef.current) {
      setCurrentDocId(docId);
      currentDocIdRef.current = docId;
      onDocumentCreated?.(docId);
    }

    // 同时写入 kb_draft_{docId} 和 kb_draft_new
    draftStorage.save(docId, { ...data, documentId: docId });
    draftStorage.save(undefined, { ...data, documentId: docId });

    setLastSavedAt(new Date());
    setSaveStatus('saved');
    hasChangesRef.current = false;

    // 3 秒后状态淡出为 idle
    setTimeout(() => {
      setSaveStatus((prev) => (prev === 'saved' ? 'idle' : prev));
    }, 3000);
  } catch (error) {
    // 后端失败 → localStorage 兜底
    draftStorage.save(currentDocIdRef.current, { ...data, documentId: currentDocIdRef.current });
    setSaveStatus('error');
  } finally {
    isSavingRef.current = false;
  }
}, [onDocumentCreated]);

草稿恢复 —— mount 时扫描 localStorage:

useEffect(() => {
  if (!enabled) return;
  // 1. 精确匹配 documentId
  let draft = draftStorage.load(initialDocId);
  // 2. 新建文档场景:扫描所有 kb_draft_* 取最新
  if (!draft && !initialDocId) {
    draft = draftStorage.findLatest();
  }
  if (draft) {
    setRecoveryDraft(draft);
    setIsRecoveryDialogOpen(true);
  }
}, []);

beforeunload 安全保障 —— 关闭标签页前同步到 localStorage:

useEffect(() => {
  const handler = (e: BeforeUnloadEvent) => {
    if (hasChangesRef.current) {
      const data = formDataRef.current;
      draftStorage.save(currentDocIdRef.current, { ...data, documentId: currentDocIdRef.current });
      draftStorage.save(undefined, { ...data, documentId: currentDocIdRef.current });
      e.preventDefault();
      e.returnValue = '';  // 触发浏览器确认对话框
    }
  };
  window.addEventListener('beforeunload', handler);
  return () => window.removeEventListener('beforeunload', handler);
}, []);

5.2 useDebounce

// src/hooks/useDebounce.ts
export function useDebounce<T>(value: T, delay: number = 300): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
}

5.3 useLocalStorage

// src/hooks/useLocalStorage.ts
export function useLocalStorage<T>(key: string, initialValue: T): [T, (v: T) => void] {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch {
      return initialValue;
    }
  });

  const setValue = (value: T) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error);
    }
  };

  return [storedValue, setValue];
}

5.4 usePagination

// src/hooks/usePagination.ts
export function usePagination(defaultPageSize: number = 12) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(defaultPageSize);

  const handlePageChange = (newPage: number, newPageSize?: number) => {
    setPage(newPage);
    if (newPageSize) setPageSize(newPageSize);
  };

  const reset = () => { setPage(1); setPageSize(defaultPageSize); };

  return { page, pageSize, handlePageChange, reset };
}

6. 浏览器存储层:Token、草稿、配置的三层存储体系

6.1 存储键一览表

键名类型来源内容
auth-storagelocalStorageZustand persist{ user, token, isAuthenticated }
access_tokenCookie + localStoragetokenStorageJWT access token
refresh_tokenCookie + localStoragetokenStorageJWT refresh token
token_typelocalStoragetokenStorage"Bearer"
expires_atlocalStoragetokenStorageToken 过期时间戳
user_infolocalStoragetokenStorageJSON 序列化的用户信息
kb_draft_{docId}localStoragedraftStorage有文档 ID 的草稿数据
kb_draft_newlocalStoragedraftStorage新建文档的草稿数据
token (legacy)localStorage兼容旧版旧版 token(作为 fallback)
user (legacy)localStorage兼容旧版旧版用户信息
system-config-storagelocalStorageFoundation Store persist系统配置 key-value map
dict-storagelocalStorageFoundation Store persist字典数据 map

6.2 草稿存储工具

// src/utils/draft-storage.ts
const DRAFT_PREFIX = 'kb_draft_';

export interface DraftData {
  title: string;
  content: string;
  summary: string;
  categoryId: string;
  teamId: string;
  tags: string[];
  visibility: string;
  allowComments: boolean;
  allowEdit: boolean;
  aiIndex: boolean;
  saveOption: 'submit_review' | 'draft';
  documentId?: string;
  savedAt: number;  // Date.now()
}

export const draftStorage = {
  save(docId, data): void    // 保存到 kb_draft_{docId} 或 kb_draft_new
  load(docId): DraftData     // 读取指定草稿
  remove(docId): void        // 删除指定草稿
  removeAll(): void          // 删除所有 kb_draft_* 草稿
  migrateToId(oldDocId, newDocId): void  // ID 迁移(new → docId)
  findLatest(): DraftData    // 扫描所有 kb_draft_* 返回最新的
}

双键保存策略 —— 每次自动保存同时写入两个 key:

autoSave() 返回 docId=12345
  → draftStorage.save("12345", data)     // kb_draft_12345
  → draftStorage.save(undefined, data)   // kb_draft_new
为什么存两份? kb_draft_12345 用于 /documents/12345/edit 编辑页面恢复;kb_draft_new 用于用户从 /documents/new 重新进入创建页面时的恢复。两个入口都能找到草稿。

7. HTTP 服务层:Axios 拦截器链与 Token 刷新队列

7.1 Axios 实例配置

// src/services/request.ts
const request: AxiosInstance = axios.create({
  baseURL: '/api',                              // Vite 代理
  timeout: 120000,                              // 2 分钟(支持文档导入长耗时)
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Accept': 'application/json;charset=UTF-8',
  },
  withCredentials: false,                       // 手动管理 Authorization Header
});

7.2 请求拦截器

请求出发
  │
  ├── skipAuth? → 跳过 Token 注入
  │
  ├── tokenStorage.getAuthorizationHeader() → "Bearer {token}"
  │     └── 为空? → 开发环境 console.warn
  │
  ├── 注入 CSRF Token(如果 meta[name="csrf-token"] 存在)
  │
  ├── X-Request-ID: {timestamp}-{random}  // 请求追踪
  │
  └── X-Requested-With: XMLHttpRequest

7.3 响应拦截器与 "脱壳"

后端统一返回格式为 { code, message, data, timestamp },响应拦截器自动脱壳:

// src/services/request.ts
request.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 200) {
        return data.data;  // 脱壳:只返回 data 字段
      }
      if (data.code === 401) {
        handleUnauthorized();
        return Promise.reject(new Error(data.message));
      }
      // 其他业务错误 → message.error() → reject
      message.error(data.message);
      return Promise.reject(new Error(data.message));
    }
    return data;  // 非标准格式,透传原始数据
  },
  (error) => { /* HTTP 状态码错误处理 */ }
);
注意:下载请求设置 _download: true 标记,响应拦截器检测到此标记时直接返回完整 AxiosResponse,以便读取 Content-Disposition 等响应头。

7.4 Token 刷新队列

这是避免"刷新风暴"的核心机制:

// src/services/request.ts
let isRefreshing = false;
let requests: Array<(token: string) => void> = [];

function handleTokenExpired(error: AxiosError): Promise<any> {
  // 1. 如果正在刷新,将当前请求加入等待队列
  if (isRefreshing) {
    return new Promise((resolve) => {
      requests.push((token: string) => {
        error.config!.headers!.Authorization = `Bearer ${token}`;
        resolve(request(error.config!));  // 用新 token 重试
      });
    });
  }

  // 2. 开始刷新
  isRefreshing = true;
  const refreshToken = tokenStorage.getRefreshToken();

  return request
    .post('/auth/auth/refresh', null, {
      params: { refreshToken },
      skipAuth: true,  // 刷新请求不使用旧 Token
    })
    .then((newTokenInfo) => {
      tokenStorage.saveToken(newTokenInfo);
      // 3. 重放等待队列中的所有请求
      requests.forEach(callback => callback(newTokenInfo.accessToken));
      requests = [];
      // 4. 重试当前请求
      error.config!.headers!.Authorization = `Bearer ${newTokenInfo.accessToken}`;
      return request(error.config!);
    })
    .catch(() => {
      tokenStorage.clearToken();
      handleUnauthorized();
    })
    .finally(() => { isRefreshing = false; });
}
请求 A (401)                                   请求 B (401)
    │                                               │
    ▼                                               ▼
isRefreshing = false                          isRefreshing = true
→ 开始刷新请求                                    → 入队等待
    │                                               │
    ▼                                               │
POST /auth/auth/refresh ──成功──→ 保存新 Token      │
    │                                               │
    ▼                                               ▼
重试请求 A ──────────────────────────────→ 重放请求 B

7.5 HTTP 工具方法封装

// src/services/request.ts
export const http = {
  get: <T>(url, config?) => request.get(url, config),
  post: <T>(url, data?, config?) => request.post(url, data, config),
  put: <T>(url, data?, config?) => request.put(url, data, config),
  delete: <T>(url, config?) => request.delete(url, config),
  patch: <T>(url, data?, config?) => request.patch(url, data, config),
  postForm: <T>(url, data: FormData) => request.post(url, data, { headers: { 'Content-Type': undefined } }),
  download: (url, filename?) => { /* blob + a 标签下载 */ },
  downloadPost: (url, data, filename?) => { /* POST 方式下载 */ },
};

8. SSE 流式状态管理:从字节流到 UI 实时渲染

8.1 为什么不用 Axios 处理 SSE

Axios 的响应拦截器会 return data.data(脱壳),但 SSE 流是逐块到达的 ReadableStream,在流完整到达前 data.data 是一个未完成的对象。同时,responseType: 'stream' 在浏览器端 Axios 不被支持。因此,SSE 流式接口全部使用原生 fetch()。

8.2 SSE 事件流解析器

// src/services/ai.service.ts
askStream: (data, onMessage, onDone?, onError?) => {
  const authHeader = tokenStorage.getAuthorizationHeader();

  return fetch(`${VITE_API_BASE_URL}/ai/chat/stream`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': authHeader,     // 手动注入 Token
    },
    body: JSON.stringify({
      content: data.question,
      conversationId: data.conversationId,
      model: data.model,
      enableRag: data.context?.knowledgeBase === true,
      enableKag: data.context?.enableKag === true,
    }),
  }).then(async (response) => {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let currentEvent = '';
    let messageLines: string[] = [];

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';  // 保留不完整的最后一行

      for (const line of lines) {
        if (line.startsWith('event:')) {
          if (messageLines.length > 0) { onMessage(messageLines.join('\n')); messageLines = []; }
          currentEvent = line.slice(6).trim();
        } else if (line.startsWith('data:')) {
          const data = line.startsWith('data: ') ? line.slice(6) : line.slice(5);
          if (currentEvent === 'error') { onError?.(data); continue; }
          if (currentEvent === 'done') { onDone?.(JSON.parse(data)); continue; }
          messageLines.push(data);  // message 事件:累加数据行
        } else if (line === '') {
          // 空行 = SSE 事件边界
          if (messageLines.length > 0) { onMessage(messageLines.join('\n')); messageLines = []; }
          currentEvent = '';
        }
      }
    }
    // 流结束:发送残留数据
    if (messageLines.length > 0) { onMessage(messageLines.join('\n')); }
  });
}

8.3 SSE 协议格式

event: message
data: RAG是检索增强生成(Retrieval-Augmented Generation)

event: message
data: 的缩写,它是一种将信息检索与

event: done
data: {"conversationId":456,"messageId":789,"content":"...","tokens":1234}

event: error
data: 模型服务超时,请稍等重试

8.4 Store 中的流式状态更新

fetch() ReadableStream
    │
    ├── event: message → onMessage(chunk)
    │     └── useAIStore.set({
    │           currentResponse: state.currentResponse + chunk  ← 逐字累加
    │         })
    │         → React 自动 re-render → UI 实时打字效果
    │
    ├── event: done → onDone({ conversationId, messageId })
    │     └── useAIStore.set({
    │           currentConversation: {
    │             id: finalConversationId,       ← 后端的权威 ID
    │             messages: [...prev, assistantMessage]
    │           },
    │           conversations: updatedList,      ← 同步侧边栏
    │           isLoading: false,
    │           isStreaming: false,
    │           currentResponse: '',
    │         })
    │
    └── event: error → onError(errorMsg)
          └── throw → catch → set({ isLoading: false, isStreaming: false })

9. WebSocket 实时推送:STOMP 订阅与 Store 更新

9.1 STOMP over SockJS 连接架构

// src/services/websocket.service.ts
class WebSocketService {
  private client: Client | null = null;
  private notificationCallbacks: Set<NotificationCallback> = new Set();
  private reviewerCallbacks: Set<NotificationCallback> = new Set();
  private reconnectAttempts = 0;
  private maxReconnect = 5;       // WS_CONFIG.maxReconnectTimes

  connect(authToken: string, isReviewer: boolean): void {
    const sockJsUrl = `/ws/notification?token=${encodeURIComponent(token)}`;

    this.client = new Client({
      webSocketFactory: () => new SockJS(sockJsUrl),
      connectHeaders: { Authorization: authToken },
      heartbeatIncoming: 30000,     // 30 秒心跳
      heartbeatOutgoing: 30000,
      reconnectDelay: 0,            // 手动控制重连

      onConnect: () => {
        // 订阅个人通知频道(点对点)
        this.client?.subscribe('/user/queue/notifications', (message) => {
          const payload = JSON.parse(message.body);
          this.notificationCallbacks.forEach(cb => cb(payload));
        });

        // 审核员额外订阅公共广播频道
        if (isReviewer) {
          this.client?.subscribe('/topic/reviewers', (message) => {
            const payload = JSON.parse(message.body);
            this.reviewerCallbacks.forEach(cb => cb(payload));
          });
        }
      },

      onDisconnect: () => this.attemptReconnect(authToken, isReviewer),
    });

    this.client.activate();
  }
}

9.2 WebSocket → Store 数据流

后端 Spring STOMP 推送
  ↓
STOMP Broker
  ├── /user/queue/notifications (点对点)
  └── /topic/reviewers (广播)
  ↓
SockJS onmessage
  ↓
STOMP IMessage.body
  ↓
WebSocketService 回调分发
  ├── notificationCallbacks → MainLayout.handleWsNotification()
  │     ├── notificationStore.addNotification(payload)
  │     │     └── set({ notifications: [notification, ...prev] })
  │     └── antd notification.info() 弹出通知
  │
  └── reviewerCallbacks → MainLayout.handleReviewerNotification()
        └── notificationStore.addNotification(payload)

9.3 自动重连机制

private attemptReconnect(authToken: string, isReviewer: boolean): void {
  if (this.reconnectAttempts >= this.maxReconnect) {
    console.warn(`已达最大重连次数 (${this.maxReconnect}),停止重连`);
    return;
  }
  this.reconnectAttempts++;
  const delay = 5000;  // 5 秒重连间隔
  setTimeout(() => {
    if (!this.connected) {
      this.connect(authToken, isReviewer);
    }
  }, delay);
}

10. 总结

#亮点说明
1Zustand 单一状态库无 Redux、无 Context API 做状态分发,12 个扁平 Store 各司其职,学习曲线极低
2Token 刷新队列isRefreshing + requests[] 队列模式,防止并发 401 触发多个 refresh 请求
3乐观更新 + 后端同步likeDocument 先翻转 UI → 再拉取真实 likeCount,兼顾响应速度与数据准确性
4useAutoSave 的 Ref 架构formDataRef + isSavingRef + hasChangesRef + saveToBackendRef 四层 Ref 消除 setInterval 闭包陷阱
5SSE 用 fetch 不用 Axios正确的技术选型:ReadableStream 不能被 Axios 响应拦截器处理
6草稿双键 + 三层兜底kb_draft_{docId} + kb_draft_new 双键保存 → findLatest() 扫描 → beforeunload 同步 → 后端兜底
7消息通知桥接message-holder.ts 模块级变量 + setMessageApi() 解决了 antd 5.x 静态方法无法消费动态主题的问题
8应用配置幂等加载loaded 标志位防止每次路由切换重新请求,失败时也标记 loaded 避免无限重试
9AI 模型降级兜底API 获取模型列表失败时使用本地 AI_CONFIG.MODELS 常量,确保用户始终有可选模型
10Map<string, boolean>** 收藏状态**O(1) 查询而非 O(n) 遍历,用户翻页收藏高频场景收益明显

前端状态管理层以 Zustand 12 Store + 4 Custom Hooks + 3 层浏览器存储 + SSE/WebSocket 双实时通道 的架构,实现了从 SSOT(Single Source of Truth)到 UI 渲染的完整状态生命周期管理。

虽然没有 React Context API 的分发层,但通过 Zustand 的 selector 机制实现了精确订阅,避免了 Context 的全量 re-render 问题。

Token 刷新队列、乐观更新与后端同步、草稿三层兜底等关键机制体现了对边界场景的充分思考。

最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏