状态机与 XState 前端实践:可视化状态、并发与持久化技术背景有限状态机(FSM)通过明确状态与迁移提高可维护性与可测试性。XState 在 FSM 之上提供层次状态、并发(parallel)与服务(invoke)能力,可用于复杂交互与流程编排。核心内容基础状态机定义与使用import { createMachine, assign } from 'xstate';
interface Ctx { user?: { id: string; name: string }; error?: string }
const authMachine = createMachine<Ctx>({
id: 'auth',
initial: 'idle',
context: {},
states: {
idle: { on: { LOGIN: 'loading' } },
loading: {
invoke: {
src: 'doLogin',
onDone: { target: 'authenticated', actions: assign({ user: (_ctx, e: any) => e.data }) },
onError: { target: 'failure', actions: assign({ error: (_ctx, e: any) => e.data?.message || 'error' }) }
}
},
authenticated: { on: { LOGOUT: { target: 'idle', actions: 'clear' } } },
failure: { on: { RETRY: 'loading' } }
}
}, {
services: {
doLogin: (_ctx, _e) => fetch('/api/login').then(r => r.json())
},
actions: {
clear: assign({ user: (_ctx) => undefined, error: (_ctx) => undefined })
}
});
并发与层次状态(parallel/compound)const appMachine = createMachine({
id: 'app',
type: 'parallel',
states: {
ui: {
initial: 'light',
states: { light: { on: { TOGGLE: 'dark' } }, dark: { on: { TOGGLE: 'light' } } }
},
data: {
initial: 'idle',
states: {
idle: { on: { LOAD: 'loading' } },
loading: { /* ... */ },
ready: {}
}
}
}
});
持久化与恢复function persistState(key: string, state: any) {
sessionStorage.setItem(key, JSON.stringify(state));
}
function restoreState(key: string) {
const raw = sessionStorage.getItem(key);
return raw ? JSON.parse(raw) : null;
}
技术验证参数在实际应用(Chrome 128/Edge 130,React 18)下:关键流程错误率:下降 30–55%状态可视化与测试覆盖率:≥ 90%恢复成功率(刷新后):≥ 95%应用场景复杂交互与多步骤流程编排并发 UI 与数据状态管理可视化与自动化测试驱动开发最佳实践明确状态与事件语义,避免隐式布尔标志使用 invoke 管理异步服务与错误处理持久化关键状态并提供恢复路径

发表评论 取消回复