码巢引擎2026年开发文档
00-开发规范
后端规范
README
后端开发手册
前端规范
README
TypeScript最佳实践
前端布局规范
前端页面模板
前端颜色与组件规范
核心规范
组件配置手册
问题排查指南
页面模板
最佳实践
README
bp-20260223-m7ps
图片上传优化总结
BUG自动记录系统使用指南
README
TYPE_SAFETY_GUIDE
常见BUG知识库
常见BUG知识库
开发前检查清单
开发安全规范
开发规范-完整版-含FutureBirdAadminAi部署
数据模型字典
文档分类规范
文档标准化规范
文档模板-基础版
文档模板-技术版
类型安全快速参考卡
类型安全规范体系
规范更新指南
过期文档清理机制
错误处理规范
错误预防指南
常见BUG知识库
常见BUG知识库
01-快速开始
Gitee快速开始
README
协作快速开始
快速开始
质量保证快速开始
02-部署指南
Docker更新指南
Docker部署
FutureBirdAadminAi部署指南
FutureBirdAadminAi部署问题分析
README
发布指南
宝塔Docker部署教程
宝塔PM2部署教程
宝塔图形化部署教程
快速发布指南
数据库和依赖变更处理指南
构建和发布
构建标准
构建检查清单
生产部署快速开始
生产部署方案
生产部署标准
生产部署检查清单
程序备份性能
自动修复和发布指南
自动化发布命令使用指南
部署快速开始
部署指南
项目更新部署指南
03-开发指南
Git凭据配置
Git推送规则
Git自动配置
README
全局样式
协作设置
定时任务
开发指南
开发流程
开发环境标准
技术改进
贡献指南
项目目录树
项目目录结构
04-API文档
API接口文档
README
hr-api
企业API
05-数据库
DATABASE_SCHEMA
README
分区指南
数据库字典
数据持久化
数据模型统一
数据迁移
06-架构设计
RBAC-PERMISSIONS
README
SaaS客户引导流程设计
companyId统一规范
employee-permission-system-design
enterprise-data-linkage
仓库实现总结
仓库模式
企业管理端员工权限系统分析
前端架构
前端重构总结
员工权限系统评估报告
员工管理菜单重构方案
权限系统混乱问题分析
架构优化计划
架构使用指南
架构结构
架构结构
状态管理
用户身份管理体系
系统架构
面试管理模块重构规划
项目技术栈
07-测试质量
README
测试修复标准
测试报告
质量保证系统
08-版本管理
CHANGELOG
README
VERSION_RULES
09-配置指南
README
SMTP配置指南
主题切换指南
渠道配置指南
环境变量指南
环境隔离
12-项目记忆
README
知识库导入指南
记忆系统指南
13-迁移指南
README
备份迁移指南
管理员迁移指南
迁移快速开始
17-其他
README
压缩摘要
18-开放平台
01-架构设计
02-API接口设计
03-安全机制
04-前端设计
05-数据库设计
开放平台API指南
开放平台API说明
19-智能进化
AI执行规则
AI进化机制
README
自动化实现总览
黄金规则
40-操作教程
README
微信公众号域名配置指南
微信本地开发调试指南
44-技能文件
alipay-payment-integration
references
checklist
SKILL
audio
python
README
typescript
README
SKILL
database
python
README
typescript
README
SKILL
design-style-thinking
SKILL
doctor
references
sql-patterns
SKILL
document-generation
python
README
SKILL
email
SKILL
embedding
python
README
typescript
README
SKILL
expo-advanced
references
audio-record-play
file-upload
masonry-layout
save-to-gallery
top-tab-navigation
SKILL
feishu-base
SKILL
feishu-message
SKILL
fetch-url
python
README
typescript
README
SKILL
frontend-design
LICENSE
SKILL
FutureBird-coding-web-performance-best-practice
SKILL
general-dev-preview
references
web-preview
SKILL
image-generation
python
README
typescript
README
SKILL
knowledge
references
python
README
typescript
README
cli
SKILL
llm
python
README
typescript
README
SKILL
miniapp-upload-asr
SKILL
pptx-generation
python
README
SKILL
project-memory-loader
scripts
project_memory_loader
SKILL
repair
scripts
merge-commit-map
SKILL
shadcn-web-base-theme
assets
colors
amber
artistic-green
bento-blue
blue
cyan
emerald
fuchsia
gray
green
indigo
lime
low-pink
neutral
orange
purple
red
retro-brown
rose
sky
supbase-green
teal
tech-purple
vintage-grey
violet
yellow
fonts
business
classic
playful
radius
2xl
2xs
lg
md
none
sm
xl
xs
shadow
artistic
bento
cool
retro
superbase
tech
tool
vintage
default
references
colors
fonts
quick
radius
shadows
scripts
theme
SKILL
package
skill-creator-coze
scripts
init_skill
quick_validate
SKILL
storage
python
README
typescript
README
SKILL
supabase
assets
supabase-client
supabase-client
references
_future
asset-supabase-browser
asset-supabase-config-inject
asset-supabase-config-route
python-auth
python-realtime
python-storage
typescript-auth
typescript-realtime
typescript-storage
typescript-supabase-browser
typescript-supabase-config-inject
typescript-supabase-config-route
python
README
database
edge-functions
orm-model-guide
supabase_client
typescript
README
database
drizzle-schema-guide
edge-functions
supabase-client
cli
rls
SKILL
supabase-auth
references
typescript
supabase-browser
supabase-config-inject
supabase-config-route
auth-config
verify-session
SKILL
ui-design-ref
reference
3D黏土风
克莱因蓝高定风
暗黑科技风
杂志风
极光柔和
柔和卡片
玻璃拟态
纯白极简风
自然有机
SKILL
ui-ux-pro-max
scripts
core
design_system
search
SKILL
vercel-composition-patterns
rules
architecture-avoid-boolean-props
architecture-compound-components
patterns-children-over-render-props
patterns-explicit-variants
react19-no-forwardref
state-context-interface
state-decouple-implementation
state-lift-state
AGENTS
SKILL
vercel-react-best-practices
rules
advanced-event-handler-refs
advanced-init-once
advanced-use-latest
async-api-routes
async-defer-await
async-dependencies
async-parallel
async-suspense-boundaries
bundle-barrel-imports
bundle-conditional
bundle-defer-third-party
bundle-dynamic-imports
bundle-preload
client-event-listeners
client-localstorage-schema
client-passive-event-listeners
client-swr-dedup
js-batch-dom-css
js-cache-function-results
js-cache-property-access
js-cache-storage
js-combine-iterations
js-early-exit
js-hoist-regexp
js-index-maps
js-length-check-first
js-min-max-loop
js-set-map-lookups
js-tosorted-immutable
rendering-activity
rendering-animate-svg-wrapper
rendering-conditional-render
rendering-content-visibility
rendering-hoist-jsx
rendering-hydration-no-flicker
rendering-hydration-suppress-warning
rendering-svg-precision
rendering-usetransition-loading
rerender-defer-reads
rerender-dependencies
rerender-derived-state-no-effect
rerender-derived-state
rerender-functional-setstate
rerender-lazy-state-init
rerender-memo-with-default-value
rerender-memo
rerender-move-effect-to-event
rerender-simple-expression-in-memo
rerender-transitions
rerender-use-ref-transient-values
server-auth-actions
server-cache-lru
server-cache-react
server-dedup-props
server-parallel-fetching
server-serialization
AGENTS
SKILL
video-edit
python
README
typescript
README
SKILL
video-generation
python
README
typescript
README
SKILL
volcano-ark
SKILL
web-design-guidelines
SKILL
web-search
python
README
typescript
README
SKILL
webrtc-best-practice
SKILL
websocket-guide
references
nextjs
nodejs
SKILL
wechat-bot
SKILL
wechat-official-account
SKILL
README
README
未来鸟:企业数字化转型奔腾的力量!
-
+
首页
状态管理
> **文档版本**: v1.0.0 > **创建日期**: 2026-02-12 > **最后更新**: 2026-02-12 > **维护人**: 未来鸟FutureBird码巢企业服务引擎开发组 > **状态**: [最新] --- # 前端状态管理方案 ## 状态分类 ### 1. 全局状态(Global State) **定义**:跨多个组件共享的状态 **管理方式**:Zustand **适用场景**: - 用户认证信息 - 用户权限信息 - 应用配置(主题、语言等) - 全局通知消息 **示例**: ```typescript // auth.store.ts interface AuthState { user: User | null; token: string | null; isAuthenticated: boolean; login: (credentials: LoginCredentials) => Promise<void>; logout: () => void; } ``` ### 2. 本地状态(Local State) **定义**:仅在单个组件或其子组件中使用的状态 **管理方式**:useState **适用场景**: - 表单输入值 - 组件显示/隐藏 - 交互状态(hover、active) - 临时数据 **示例**: ```typescript const [isOpen, setIsOpen] = useState(false); const [formData, setFormData] = useState({}); ``` ### 3. 服务端状态(Server State) **定义**:从服务器获取的数据 **管理方式**:React Query(TanStack Query) **适用场景**: - 从API获取的数据 - 需要缓存和重新验证的数据 - 需要乐观更新的数据 **示例**: ```typescript const { data, isLoading, error } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }); ``` ### 4. 表单状态(Form State) **定义**:表单输入和验证状态 **管理方式**:React Hook Form **适用场景**: - 表单输入 - 表单验证 - 表单提交 **示例**: ```typescript const { register, handleSubmit, formState: { errors } } = useForm(); ``` ## 技术选型 ### 1. Zustand - 全局状态管理 **优势**: - 简洁轻量(~1KB) - 无需Provider包装 - 支持TypeScript - 支持中间件(persist、devtools等) - 性能优秀 **安装**: ```bash pnpm add zustand pnpm add -D @types/zustand ``` ### 2. React Query - 服务端状态管理 **优势**: - 自动缓存和重新验证 - 乐观更新 - 分页和无限滚动 - 自动重试 - 离线支持 **安装**: ```bash pnpm add @tanstack/react-query ``` ### 3. React Hook Form - 表单状态管理 **优势**: - 性能优秀(减少重渲染) - 内置验证 - 支持复杂表单 - 与Zod集成良好 **安装**: ```bash pnpm add react-hook-form pnpm add @hookform/resolvers zod ``` ## Zustand Store 设计 ### Store目录结构 ``` src/stores/ ├── auth.store.ts # 认证状态 ├── user.store.ts # 用户状态 ├── tenant.store.ts # 租户状态 ├── ui.store.ts # UI状态 ├── notification.store.ts # 通知状态 └── index.ts # 统一导出 ``` ### Store创建模板 ```typescript import { create } from 'zustand'; import { persist } from 'zustand/middleware'; interface StoreState { // 状态 state: any; // 操作 action: () => void; } export const useStore = create<StoreState>()( persist( (set, get) => ({ // 状态 state: null, // 操作 action: () => { set({ state: newValue }); } }), { name: 'store-name', // localStorage key partialize: (state) => ({ state: state.state }) // 只持久化部分状态 } ) ); ``` ## React Query 设计 ### QueryClient配置 ```typescript import { QueryClient } from '@tanstack/react-query'; export const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, // 5分钟 retry: 1, refetchOnWindowFocus: false, }, }, }); ``` ### Query Keys设计 ```typescript // keys.ts export const queryKeys = { auth: ['auth'] as const, user: (id: string) => ['users', id] as const, users: () => ['users'] as const, tenant: (id: string) => ['tenants', id] as const, salarySlips: (params?: any) => ['salary-slips', params] as const, } as const; ``` ## 自定义Hooks设计 ### Hooks目录结构 ``` src/hooks/ ├── useAuth.ts # 认证Hook ├── useUser.ts # 用户Hook ├── useTenant.ts # 租户Hook ├── useApi.ts # API调用Hook ├── usePagination.ts # 分页Hook ├── useTable.ts # 表格Hook ├── useForm.ts # 表单Hook ├── useDebounce.ts # 防抖Hook ├── useLocalStorage.ts # 本地存储Hook └── index.ts # 统一导出 ``` ### Hook创建模板 ```typescript import { useStore } from '@/stores'; export const useCustomHook = () => { const { state, action } = useStore(); const doSomething = useCallback(() => { action(); }, [action]); return { state, doSomething }; }; ``` ## 状态管理最佳实践 ### 1. 选择正确的状态管理方式 | 状态类型 | 推荐方案 | |---------|---------| | 跨组件共享 | Zustand | | API数据 | React Query | | 表单数据 | React Hook Form | | 组件内部 | useState | | UI状态(theme、language) | Zustand + Context | ### 2. 避免过度使用全局状态 - 优先使用本地状态 - 只有真正需要跨组件共享时才使用全局状态 ### 3. 合理使用React Query - 利用缓存减少不必要的请求 - 使用invalidateQueries刷新数据 - 使用optimistic updates优化用户体验 ### 4. 保持Store简单 - 避免在Store中包含过多逻辑 - 复杂逻辑抽离为独立的Hook ### 5. 类型安全 - 为所有Store和Hook定义明确的TypeScript类型 - 使用as const确保类型推断 ## 示例:完整的认证流程 ```typescript // 1. Auth Store export const useAuthStore = create<AuthState>()( persist( (set) => ({ user: null, token: null, isAuthenticated: false, login: async (credentials) => { const response = await authApi.login(credentials); set({ user: response.user, token: response.token, isAuthenticated: true }); }, logout: () => { set({ user: null, token: null, isAuthenticated: false }); } }), { name: 'auth-storage' } ) ); // 2. Auth Hook export const useAuth = () => { const { user, token, isAuthenticated, login, logout } = useAuthStore(); return { user, token, isAuthenticated, login, logout }; }; // 3. 在组件中使用 function LoginPage() { const { login } = useAuth(); const [loading, setLoading] = useState(false); const handleSubmit = async (data: LoginForm) => { setLoading(true); try { await login(data); router.push('/dashboard'); } catch (error) { console.error(error); } finally { setLoading(false); } }; return <LoginForm onSubmit={handleSubmit} />; } ``` ## 总结 通过合理的状态管理方案,我们可以: 1. **提高代码可维护性**:清晰的状态分类和职责划分 2. **提升性能**:减少不必要的重渲染 3. **改善开发体验**:简洁的API和良好的TypeScript支持 4. **增强用户体验**:合理的数据缓存和更新策略
未来鸟
2026年7月27日 10:36
转发
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
分享
链接
类型
密码
更新密码
有效期
Markdown文件
Word文件
PDF文档(打印)
AI