第4章 状态管理与数据流架构:AI辅助的状态设计
4.1 本地状态管理的类型策略与AI生成
本地状态管理是React应用的基础,选择合适的状态管理策略对于应用的可维护性至关重要。TypeScript的类型系统可以帮助我们做出更明智的决策。
4.1.1 useState与useReducer的选择决策树
useState和useReducer是React提供的两个基础状态管理Hook,它们各有适用的场景。
选择决策树
TEXT1状态管理Hook选择决策树: 2 3状态类型是什么? 4├── 简单值类型(string, number, boolean) 5│ └── 使用 useState 6│ 7├── 对象类型,更新逻辑简单 8│ └── 使用 useState + 展开运算符 9│ 10├── 对象类型,更新逻辑复杂 11│ └── 使用 useReducer 12│ 13├── 多个相关状态需要一起更新 14│ └── 使用 useReducer 15│ 16└── 状态转换有明确的业务规则 17 └── 使用 useReducer + Immer
简单值类型vs复杂状态机的Reducer模式
TYPESCRIPT1// 场景1:简单值类型 - useState 2function Counter() { 3 const [count, setCount] = useState(0); 4 5 return ( 6 <div> 7 <p>{count}</p> 8 <button onClick={() => setCount(c => c + 1)}>+</button> 9 <button onClick={() => setCount(c => c - 1)}>-</button> 10 </div> 11 ); 12} 13 14// 场景2:复杂状态机 - useReducer 15interface FormState { 16 values: { username: string; password: string }; 17 errors: { username?: string; password?: string }; 18 touched: { username: boolean; password: boolean }; 19 isSubmitting: boolean; 20 isValid: boolean; 21} 22 23type FormAction = 24 | { type: 'SET_FIELD'; field: string; value: string } 25 | { type: 'SET_ERROR'; field: string; error: string } 26 | { type: 'SET_TOUCHED'; field: string } 27 | { type: 'SUBMIT_START' } 28 | { type: 'SUBMIT_SUCCESS' } 29 | { type: 'SUBMIT_ERROR'; error: string }; 30 31function formReducer(state: FormState, action: FormAction): FormState { 32 switch (action.type) { 33 case 'SET_FIELD': 34 return { 35 ...state, 36 values: { ...state.values, [action.field]: action.value }, 37 }; 38 case 'SET_ERROR': 39 return { 40 ...state, 41 errors: { ...state.errors, [action.field]: action.error }, 42 }; 43 case 'SET_TOUCHED': 44 return { 45 ...state, 46 touched: { ...state.touched, [action.field]: true }, 47 }; 48 case 'SUBMIT_START': 49 return { ...state, isSubmitting: true }; 50 case 'SUBMIT_SUCCESS': 51 return { ...state, isSubmitting: false, values: { username: '', password: '' } }; 52 case 'SUBMIT_ERROR': 53 return { ...state, isSubmitting: false }; 54 default: 55 return state; 56 } 57} 58 59function LoginForm() { 60 const [state, dispatch] = useReducer(formReducer, { 61 values: { username: '', password: '' }, 62 errors: {}, 63 touched: {}, 64 isSubmitting: false, 65 isValid: false, 66 }); 67 68 // 使用dispatch更新状态 69}
Immer的集成类型与不可变更新
TYPESCRIPT1import produce from 'immer'; 2 3// 使用Immer简化Reducer 4function formReducerWithImmer( 5 state: FormState, 6 action: FormAction 7): FormState { 8 return produce(state, (draft) => { 9 switch (action.type) { 10 case 'SET_FIELD': 11 draft.values[action.field] = action.value; 12 break; 13 case 'SET_ERROR': 14 draft.errors[action.field] = action.error; 15 break; 16 case 'SET_TOUCHED': 17 draft.touched[action.field] = true; 18 break; 19 case 'SUBMIT_START': 20 draft.isSubmitting = true; 21 break; 22 case 'SUBMIT_SUCCESS': 23 draft.isSubmitting = false; 24 draft.values = { username: '', password: '' }; 25 break; 26 } 27 }); 28} 29 30// Immer的类型推导 31type Draft<T> = T extends object ? { -readonly [K in keyof T]: Draft<T[K]> } : T; 32// produce函数返回的类型与输入类型相同
PlantUML图示:useState vs useReducer选择流程
渲染图表...
4.1.2 状态提升(Lifting State Up)的类型传播
状态提升是React中共享状态的标准模式,TypeScript的类型系统确保状态在组件树中正确传播。
跨组件状态共享的类型一致性保障
TYPESCRIPT1// 状态定义 2interface TemperatureState { 3 temperature: number; 4 scale: 'c' | 'f'; 5} 6 7// 父组件持有状态 8function Calculator() { 9 const [state, setState] = useState<TemperatureState>({ 10 temperature: 0, 11 scale: 'c', 12 }); 13 14 const handleCelsiusChange = (temperature: number) => { 15 setState({ temperature, scale: 'c' }); 16 }; 17 18 const handleFahrenheitChange = (temperature: number) => { 19 setState({ temperature, scale: 'f' }); 20 }; 21 22 const celsius = state.scale === 'f' ? convert(state.temperature, toCelsius) : state.temperature; 23 const fahrenheit = state.scale === 'c' ? convert(state.temperature, toFahrenheit) : state.temperature; 24 25 return ( 26 <div> 27 <TemperatureInput 28 scale="c" 29 temperature={celsius} 30 onTemperatureChange={handleCelsiusChange} 31 /> 32 <TemperatureInput 33 scale="f" 34 temperature={fahrenheit} 35 onTemperatureChange={handleFahrenheitChange} 36 /> 37 </div> 38 ); 39} 40 41// 子组件Props类型 42interface TemperatureInputProps { 43 scale: 'c' | 'f'; 44 temperature: number; 45 onTemperatureChange: (temperature: number) => void; 46} 47 48function TemperatureInput({ scale, temperature, onTemperatureChange }: TemperatureInputProps) { 49 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { 50 onTemperatureChange(parseFloat(e.target.value)); 51 }; 52 53 return ( 54 <fieldset> 55 <legend>Enter temperature in {scale === 'c' ? 'Celsius' : 'Fahrenheit'}:</legend> 56 <input value={temperature} onChange={handleChange} /> 57 </fieldset> 58 ); 59}
Co-location状态与全局状态的边界
TYPESCRIPT1// 状态位置决策矩阵 2 3/** 4 * 状态位置原则: 5 * 6 * 1. Co-location(组件本地) 7 * - 只被单个组件使用 8 * - 不需要持久化 9 * - 生命周期与组件绑定 10 * 11 * 2. 父组件提升 12 * - 被多个兄弟组件共享 13 * - 需要协调子组件状态 14 * 15 * 3. Context 16 * - 被跨层级组件共享 17 * - 主题、认证等全局状态 18 * 19 * 4. 全局状态管理(Redux/Zustand) 20 * - 跨页面共享 21 * - 需要持久化 22 * - 复杂的状态逻辑 23 */ 24 25// Co-location示例 26function useLocalFormState() { 27 const [values, setValues] = useState<Record<string, string>>({}); 28 const [errors, setErrors] = useState<Record<string, string>>({}); 29 30 // 只在组件内部使用 31 return { values, setValues, errors, setErrors }; 32} 33 34// Context示例 35interface ThemeContextValue { 36 theme: Theme; 37 setTheme: (theme: Theme) => void; 38} 39 40const ThemeContext = createContext<ThemeContextValue | null>(null); 41 42// 全局状态示例 43interface AppState { 44 user: User | null; 45 cart: CartItem[]; 46 notifications: Notification[]; 47} 48 49const useAppStore = create<AppState>(() => ({ 50 user: null, 51 cart: [], 52 notifications: [], 53}));
4.1.3 派生状态的计算缓存
派生状态(Derived State)是从现有状态计算得出的状态,合理使用缓存可以避免不必要的重计算。
useMemo与计算属性的区别
TYPESCRIPT1// 场景:购物车计算 2interface CartItem { 3 id: string; 4 price: number; 5 quantity: number; 6 discount?: number; 7} 8 9function ShoppingCart({ items }: { items: CartItem[] }) { 10 // 不使用useMemo:每次渲染都重新计算 11 const totalWithoutMemo = items.reduce( 12 (sum, item) => sum + item.price * item.quantity * (1 - (item.discount || 0)), 13 0 14 ); 15 16 // 使用useMemo:只在items变化时计算 17 const { subtotal, discount, total } = useMemo(() => { 18 const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0); 19 const discount = items.reduce( 20 (sum, item) => sum + item.price * item.quantity * (item.discount || 0), 21 0 22 ); 23 const total = subtotal - discount; 24 return { subtotal, discount, total }; 25 }, [items]); 26 27 // 使用useCallback缓存事件处理器 28 const handleCheckout = useCallback(() => { 29 // 使用total 30 checkout(total); 31 }, [total]); 32 33 return ( 34 <div> 35 <p>Subtotal: ${subtotal.toFixed(2)}</p> 36 <p>Discount: ${discount.toFixed(2)}</p> 37 <p>Total: ${total.toFixed(2)}</p> 38 <button onClick={handleCheckout}>Checkout</button> 39 </div> 40 ); 41}
引用稳定性与重渲染触发条件的AI辅助优化建议
TYPESCRIPT1// AI辅助优化建议示例 2 3/** 4 * 优化建议1:避免在useMemo中创建新对象 5 * 问题:每次返回新对象,导致子组件重渲染 6 */ 7const badExample = useMemo(() => ({ 8 total: calculateTotal(items), 9 count: items.length, 10}), [items]); 11 12// 优化:分别缓存 13const total = useMemo(() => calculateTotal(items), [items]); 14const count = useMemo(() => items.length, [items]); 15 16/** 17 * 优化建议2:注意依赖数组的完整性 18 * 问题:缺少依赖导致陈旧闭包 19 */ 20const badCallback = useCallback(() => { 21 console.log(currentPage); // 可能使用过期的currentPage 22}, []); // 缺少currentPage依赖 23 24// 优化:包含所有依赖 25const goodCallback = useCallback(() => { 26 console.log(currentPage); 27}, [currentPage]); 28 29/** 30 * 优化建议3:使用函数式更新避免依赖 31 */ 32const [count, setCount] = useState(0); 33 34// 不好的做法:需要count作为依赖 35const increment = useCallback(() => { 36 setCount(count + 1); 37}, [count]); 38 39// 优化:使用函数式更新 40const increment = useCallback(() => { 41 setCount(c => c + 1); 42}, []); // 不需要依赖
4.2 跨组件通信的类型安全方案
跨组件通信是React应用中的常见需求,TypeScript的类型系统可以确保通信的类型安全。
4.2.1 Context API的泛型约束
Context API是React提供的跨组件状态共享机制,泛型约束确保Context的类型安全。
createContext的Non-null断言与默认值设计
TYPESCRIPT1// 问题:Context的默认值可能导致运行时错误 2const ThemeContext = createContext<Theme>('light'); // 简单默认值 3 4function useTheme() { 5 const theme = useContext(ThemeContext); 6 return theme; // 类型是Theme,但可能是默认值 7} 8 9// 更好的做法:使用null和类型守卫 10interface ThemeContextValue { 11 theme: Theme; 12 setTheme: (theme: Theme) => void; 13} 14 15const ThemeContext = createContext<ThemeContextValue | null>(null); 16 17// 类型安全的Hook 18function useTheme(): ThemeContextValue { 19 const context = useContext(ThemeContext); 20 if (context === null) { 21 throw new Error('useTheme must be used within a ThemeProvider'); 22 } 23 return context; 24} 25 26// Provider实现 27interface ThemeProviderProps { 28 children: React.ReactNode; 29 initialTheme?: Theme; 30} 31 32function ThemeProvider({ children, initialTheme = 'light' }: ThemeProviderProps) { 33 const [theme, setTheme] = useState<Theme>(initialTheme); 34 35 const value = useMemo(() => ({ theme, setTheme }), [theme]); 36 37 return ( 38 <ThemeContext.Provider value={value}> 39 {children} 40 </ThemeContext.Provider> 41 ); 42}
泛型参数在Provider中的传递与消费
TYPESCRIPT1// 泛型Context定义 2interface DataContextValue<T> { 3 data: T | null; 4 loading: boolean; 5 error: Error | null; 6 refetch: () => Promise<void>; 7} 8 9function createDataContext<T>() { 10 const Context = createContext<DataContextValue<T> | null>(null); 11 12 function useDataContext(): DataContextValue<T> { 13 const context = useContext(Context); 14 if (!context) { 15 throw new Error('useDataContext must be used within Provider'); 16 } 17 return context; 18 } 19 20 return [Context.Provider, useDataContext] as const; 21} 22 23// 使用 24interface User { 25 id: string; 26 name: string; 27} 28 29const [UserProvider, useUser] = createDataContext<User>(); 30 31// 在组件中使用 32function UserProfile() { 33 const { data: user, loading, error } = useUser(); 34 35 if (loading) return <Loading />; 36 if (error) return <Error message={error.message} />; 37 if (!user) return <NotFound />; 38 39 return <div>{user.name}</div>; // 类型安全 40}
4.2.2 发布订阅模式的类型保障
发布订阅模式(Pub/Sub)是一种灵活的组件通信方式,类型系统确保事件和数据的类型安全。
EventEmitter的泛型封装与类型化事件映射
TYPESCRIPT1// 类型化事件映射 2type EventMap = { 3 'user:login': { userId: string; timestamp: number }; 4 'user:logout': { userId: string }; 5 'cart:updated': { items: CartItem[]; total: number }; 6 'notification:received': Notification; 7}; 8 9// 类型安全的EventEmitter 10class TypedEventEmitter<Events extends Record<string, any>> { 11 private listeners: { 12 [K in keyof Events]?: Array<(data: Events[K]) => void>; 13 } = {}; 14 15 on<K extends keyof Events>( 16 event: K, 17 listener: (data: Events[K]) => void 18 ): () => void { 19 if (!this.listeners[event]) { 20 this.listeners[event] = []; 21 } 22 this.listeners[event]!.push(listener); 23 24 return () => this.off(event, listener); 25 } 26 27 off<K extends keyof Events>( 28 event: K, 29 listener: (data: Events[K]) => void 30 ): void { 31 const listeners = this.listeners[event]; 32 if (listeners) { 33 const index = listeners.indexOf(listener); 34 if (index > -1) { 35 listeners.splice(index, 1); 36 } 37 } 38 } 39 40 emit<K extends keyof Events>(event: K, data: Events[K]): void { 41 const listeners = this.listeners[event]; 42 if (listeners) { 43 listeners.forEach((listener) => listener(data)); 44 } 45 } 46} 47 48// 创建全局事件总线 49const eventBus = new TypedEventEmitter<EventMap>(); 50 51// 使用 52function LoginButton() { 53 const handleLogin = () => { 54 // 类型安全的事件发射 55 eventBus.emit('user:login', { 56 userId: '123', 57 timestamp: Date.now(), 58 }); 59 }; 60 61 return <button onClick={handleLogin}>Login</button>; 62} 63 64function ActivityLog() { 65 useEffect(() => { 66 // 类型安全的事件监听 67 const unsubscribe = eventBus.on('user:login', (data) => { 68 console.log(`User ${data.userId} logged in at ${data.timestamp}`); 69 }); 70 71 return unsubscribe; 72 }, []); 73 74 return <div>...</div>; 75}
事件名到Payload的映射类型与类型安全的事件总线
TYPESCRIPT1// 更高级的事件总线类型 2type EventPayload<T> = T extends { payload: infer P } ? P : never; 3 4type EventHandler<T> = (payload: T) => void; 5 6interface EventBus<Events extends Record<string, any>> { 7 on<K extends keyof Events>( 8 event: K, 9 handler: EventHandler<Events[K]> 10 ): () => void; 11 12 once<K extends keyof Events>( 13 event: K, 14 handler: EventHandler<Events[K]> 15 ): void; 16 17 emit<K extends keyof Events>( 18 event: K, 19 payload: Events[K] 20 ): void; 21 22 off<K extends keyof Events>( 23 event: K, 24 handler: EventHandler<Events[K]> 25 ): void; 26} 27 28// React Hook封装 29function useEvent<K extends keyof EventMap>( 30 event: K, 31 handler: (data: EventMap[K]) => void 32) { 33 useEffect(() => { 34 return eventBus.on(event, handler); 35 }, [event, handler]); 36} 37 38// 使用 39function CartWatcher() { 40 useEvent('cart:updated', ({ items, total }) => { 41 // items和total都有正确的类型 42 console.log(`Cart has ${items.length} items, total: $${total}`); 43 }); 44 45 return null; 46}
4.2.3 Refs转发与命令式接口
Refs转发允许父组件访问子组件的DOM节点或实例方法,这在某些场景下是必要的。
useImperativeHandle的类型定义与forwardRef的泛型参数
TYPESCRIPT1import { forwardRef, useImperativeHandle, useRef } from 'react'; 2 3// 定义命令式接口 4interface InputFieldRef { 5 focus: () => void; 6 blur: () => void; 7 clear: () => void; 8 getValue: () => string; 9 setValue: (value: string) => void; 10 validate: () => boolean; 11} 12 13interface InputFieldProps { 14 label: string; 15 required?: boolean; 16 validator?: (value: string) => string | null; 17} 18 19// forwardRef的泛型参数:RefType, PropsType 20const InputField = forwardRef<InputFieldRef, InputFieldProps>( 21 ({ label, required, validator }, ref) => { 22 const inputRef = useRef<HTMLInputElement>(null); 23 const [error, setError] = useState<string | null>(null); 24 25 useImperativeHandle(ref, () => ({ 26 focus: () => inputRef.current?.focus(), 27 blur: () => inputRef.current?.blur(), 28 clear: () => { 29 if (inputRef.current) { 30 inputRef.current.value = ''; 31 } 32 }, 33 getValue: () => inputRef.current?.value ?? '', 34 setValue: (value) => { 35 if (inputRef.current) { 36 inputRef.current.value = value; 37 } 38 }, 39 validate: () => { 40 const value = inputRef.current?.value ?? ''; 41 if (required && !value) { 42 setError('This field is required'); 43 return false; 44 } 45 if (validator) { 46 const error = validator(value); 47 if (error) { 48 setError(error); 49 return false; 50 } 51 } 52 setError(null); 53 return true; 54 }, 55 })); 56 57 return ( 58 <div> 59 <label>{label}</label> 60 <input ref={inputRef} /> 61 {error && <span className="error">{error}</span>} 62 </div> 63 ); 64 } 65); 66 67// 使用 68function Form() { 69 const inputRef = useRef<InputFieldRef>(null); 70 71 const handleSubmit = () => { 72 const isValid = inputRef.current?.validate(); 73 if (isValid) { 74 const value = inputRef.current?.getValue(); 75 // 提交表单 76 } 77 }; 78 79 return ( 80 <form onSubmit={handleSubmit}> 81 <InputField ref={inputRef} label="Username" required /> 82 <button type="submit">Submit</button> 83 </form> 84 ); 85}
组件暴露方法的类型契约与AI生成的ref接口
TYPESCRIPT1// AI生成ref接口的Prompt模板 2 3/** 4 * 需求:创建一个可复用的Modal组件,支持命令式打开/关闭 5 * 6 * AI生成目标: 7 * 1. 定义ModalRef接口 8 * 2. 实现forwardRef组件 9 * 3. 使用useImperativeHandle暴露方法 10 */ 11 12// AI生成的代码 13interface ModalRef { 14 open: (options?: { title?: string; content?: React.ReactNode }) => void; 15 close: () => void; 16 toggle: () => void; 17 isOpen: () => boolean; 18} 19 20interface ModalProps { 21 defaultTitle?: string; 22 onOpen?: () => void; 23 onClose?: () => void; 24 children?: React.ReactNode; 25} 26 27const Modal = forwardRef<ModalRef, ModalProps>( 28 ({ defaultTitle, onOpen, onClose, children }, ref) => { 29 const [isOpen, setIsOpen] = useState(false); 30 const [title, setTitle] = useState(defaultTitle); 31 const [content, setContent] = useState<React.ReactNode>(children); 32 33 useImperativeHandle(ref, () => ({ 34 open: (options) => { 35 if (options?.title) setTitle(options.title); 36 if (options?.content) setContent(options.content); 37 setIsOpen(true); 38 onOpen?.(); 39 }, 40 close: () => { 41 setIsOpen(false); 42 onClose?.(); 43 }, 44 toggle: () => { 45 setIsOpen((prev) => { 46 const next = !prev; 47 if (next) onOpen?.(); 48 else onClose?.(); 49 return next; 50 }); 51 }, 52 isOpen: () => isOpen, 53 })); 54 55 if (!isOpen) return null; 56 57 return ( 58 <div className="modal-overlay"> 59 <div className="modal"> 60 <h2>{title}</h2> 61 <div className="modal-content">{content}</div> 62 </div> 63 </div> 64 ); 65 } 66);
4.3 AI驱动的状态架构设计
AI不仅可以辅助代码生成,还可以辅助状态架构的设计和决策。
4.3.1 从需求文档生成状态机
状态机是管理复杂状态的有力工具,AI可以从需求文档中自动提取状态并生成状态机定义。
XState与TypeScript的集成
TYPESCRIPT1import { createMachine, interpret, assign } from 'xstate'; 2 3// 需求:"创建一个文件上传组件,支持选择文件、上传中、上传成功、上传失败状态" 4 5// AI生成的状态机 6interface FileUploadContext { 7 file: File | null; 8 progress: number; 9 error: string | null; 10 url: string | null; 11} 12 13type FileUploadEvent = 14 | { type: 'SELECT_FILE'; file: File } 15 | { type: 'UPLOAD' } 16 | { type: 'PROGRESS'; progress: number } 17 | { type: 'SUCCESS'; url: string } 18 | { type: 'FAILURE'; error: string } 19 | { type: 'RETRY' } 20 | { type: 'RESET' }; 21 22const fileUploadMachine = createMachine({ 23 id: 'fileUpload', 24 initial: 'idle', 25 context: { 26 file: null, 27 progress: 0, 28 error: null, 29 url: null, 30 } satisfies FileUploadContext, 31 states: { 32 idle: { 33 on: { 34 SELECT_FILE: { 35 target: 'selected', 36 actions: assign({ file: (_, event) => event.file }), 37 }, 38 }, 39 }, 40 selected: { 41 on: { 42 UPLOAD: 'uploading', 43 SELECT_FILE: { 44 actions: assign({ file: (_, event) => event.file }), 45 }, 46 }, 47 }, 48 uploading: { 49 on: { 50 PROGRESS: { 51 actions: assign({ progress: (_, event) => event.progress }), 52 }, 53 SUCCESS: { 54 target: 'success', 55 actions: assign({ url: (_, event) => event.url }), 56 }, 57 FAILURE: { 58 target: 'error', 59 actions: assign({ error: (_, event) => event.error }), 60 }, 61 }, 62 }, 63 success: { 64 on: { 65 RESET: 'idle', 66 }, 67 }, 68 error: { 69 on: { 70 RETRY: 'uploading', 71 SELECT_FILE: { 72 target: 'selected', 73 actions: assign({ file: (_, event) => event.file, error: null }), 74 }, 75 }, 76 }, 77 }, 78}); 79 80// React集成 81function useFileUpload() { 82 const [state, send] = useMachine(fileUploadMachine); 83 84 return { 85 state: state.value, 86 context: state.context, 87 selectFile: (file: File) => send({ type: 'SELECT_FILE', file }), 88 upload: () => send('UPLOAD'), 89 retry: () => send('RETRY'), 90 reset: () => send('RESET'), 91 }; 92}
AI从用户故事生成状态图与状态类型
MARKDOWN1# AI状态机生成Prompt 2 3## 用户故事 4作为用户,我希望能够: 51. 浏览商品列表 62. 将商品添加到购物车 73. 修改购物车中的商品数量 84. 从购物车移除商品 95. 提交订单 106. 查看订单状态 11 12## 输出要求 131. 识别所有可能的状态 142. 定义状态之间的转换 153. 识别上下文数据 164. 生成XState状态机代码 175. 生成TypeScript类型定义 18 19## 输出格式 20```typescript 21// 上下文类型 22interface Context { ... } 23 24// 事件类型 25type Event = ...; 26 27// 状态机 28const machine = createMachine({ ... });
TEXT1 2#### 4.3.2 状态管理的选型决策树 3 4AI可以基于项目特征推荐合适的状态管理方案。 5 6**基于项目规模、团队熟悉度、性能需求的LLM推荐系统** 7 8```typescript 9// 状态管理选型决策矩阵 10 11/** 12 * 决策因素: 13 * 14 * 1. 项目规模 15 * - 小型(<10个组件):useState/useReducer 16 * - 中型(10-50个组件):Context + useReducer 17 * - 大型(>50个组件):Redux/Zustand/Recoil 18 * 19 * 2. 状态复杂度 20 * - 简单:useState 21 * - 中等:useReducer 22 * - 复杂:Redux + Redux Toolkit 23 * 24 * 3. 跨组件共享需求 25 * - 局部:Co-location 26 * - 跨分支:Context 27 * - 全局:全局状态管理 28 * 29 * 4. 性能要求 30 * - 一般:任何方案 31 * - 高频更新:Recoil/Jotai(原子化) 32 * - 大量数据:Zustand(选择性订阅) 33 * 34 * 5. 团队熟悉度 35 * - 新手友好:Zustand 36 * - 经验丰富:Redux 37 * - 函数式偏好:Recoil/Jotai 38 */ 39 40// AI推荐函数示例 41interface ProjectProfile { 42 componentCount: number; 43 teamSize: number; 44 stateComplexity: 'simple' | 'medium' | 'complex'; 45 updateFrequency: 'low' | 'medium' | 'high'; 46 teamExperience: 'beginner' | 'intermediate' | 'advanced'; 47} 48 49function recommendStateManagement(profile: ProjectProfile): string { 50 const { componentCount, stateComplexity, updateFrequency, teamExperience } = profile; 51 52 // 小型项目 53 if (componentCount < 10) { 54 return 'useState/useReducer'; 55 } 56 57 // 中型项目 58 if (componentCount < 50) { 59 if (stateComplexity === 'complex') { 60 return 'Context + useReducer'; 61 } 62 return 'Zustand'; 63 } 64 65 // 大型项目 66 if (updateFrequency === 'high') { 67 return 'Recoil/Jotai'; 68 } 69 70 if (teamExperience === 'advanced') { 71 return 'Redux Toolkit'; 72 } 73 74 return 'Zustand'; 75}
PlantUML图示:状态管理选型决策树
渲染图表...
本章深入探讨了React状态管理的类型策略和AI辅助设计。从useState与useReducer的选择决策,到状态提升的类型传播,再到跨组件通信的类型安全方案,我们建立了完整的本地状态管理知识体系。同时,我们探讨了AI如何辅助状态机生成和状态管理选型,为AI-Native开发提供了实践指导。
状态管理是React应用的核心,类型安全的状态管理不仅能够减少运行时错误,还能够提高AI代码生成的质量。在下一部分中,我们将深入探讨Hooks原理、副作用工程和并发特性,建立对React运行机制的深层理解。