文章目录
-
- 一、什么是有限状态机?
- [二、为什么前端需要 FSM?](#二、为什么前端需要 FSM?)
- 三、实战案例
-
- [3.1 按钮状态机](#3.1 按钮状态机)
- [3.2 多步骤表单](#3.2 多步骤表单)
- [3.3 React 中的状态机](#3.3 React 中的状态机)
在前端开发中,我们经常要处理「状态切换」的问题:按钮点击后的变化、多步骤表单的流转、复杂组件的展开收起...... 如果用 if/else 或 switch 去处理,很快就会变得杂乱无章。
这时候,有限状态机(Finite State Machine, FSM) 是一种更优雅的方式。
一、什么是有限状态机?
有限状态机是一种数学模型,描述了一个系统在有限个状态之间,根据事件发生转移 的行为。
它的核心要素有:
- 状态(State):当前系统处于的情况。
- 初始状态(Initial State):系统一开始的状态。
- 事件(Event):触发状态切换的动作。
- 转移(Transition):状态和事件之间的映射规则。
一句话总结:
有限状态机就是 「状态 + 事件 = 新状态」 的模型。
比如交通灯系统:
css
[红灯]
↓
[绿灯]
↓
[黄灯]
↓
[红灯] ...
三个状态,按顺序循环切换。
二、为什么前端需要 FSM?
前端里充满了状态管理问题:
- 按钮:普通 → 加载中 → 成功/失败
- 表单:第 1 步 → 第 2 步 → 第 3 步 → 完成
- 订单:待支付 → 已支付 → 已发货 → 已完成
如果全靠 if/else,很快会陷入"状态地狱"。 FSM 的好处是:状态和转移规则一目了然。
三、实战案例
3.1 按钮状态机
一个按钮有四种状态:
idle(默认)loading(加载中)success(成功)error(失败)
我们可以用一个「状态表」来管理:
js
// 按钮状态机
const fsm = {
idle: { click: "loading" },
loading: { success: "success", failure: "error" },
success: { reset: "idle" },
error: { reset: "idle" }
};
let state = "idle"; // 初始状态
function transition(event) {
const next = fsm[state][event];
if (next) {
state = next;
console.log(`事件: ${event}, 新状态: ${state}`);
} else {
console.log(`事件: ${event} 无效,仍在状态: ${state}`);
}
}
// 测试
transition("click"); // idle -> loading
transition("success"); // loading -> success
transition("reset"); // success -> idle
这个例子完全可运行,比 if/else 更直观。
3.2 多步骤表单
一个三步骤注册表单:
- 输入邮箱
- 输入验证码
- 设置密码
最后到 完成 (done) 状态。
js
// 表单状态机
const fsm = {
step1: { next: "step2" },
step2: { next: "step3" },
step3: { next: "done" },
done: {}
};
let state = "step1";
function nextStep() {
const next = fsm[state].next;
if (next) {
state = next;
console.log(`切换到: ${state}`);
} else {
console.log("流程已结束");
}
}
// 测试
nextStep(); // step2
nextStep(); // step3
nextStep(); // done
nextStep(); // 流程已结束
这样就能保证表单不会跳过某一步或乱序执行。
3.3 React 中的状态机
在 React 中,FSM 也能用。比如我们实现一个「按钮」:
js
import React, { useState } from "react";
const fsm = {
idle: { click: "loading" },
loading: { success: "success", failure: "error" },
success: { reset: "idle" },
error: { reset: "idle" }
};
export default function App() {
const [state, setState] = useState("idle");
function send(event) {
const next = fsm[state][event];
if (next) setState(next);
}
return (
<div>
<p>当前状态: {state}</p>
{state === "idle" && <button onClick={() => send("click")}>提交</button>}
{state === "loading" && (
<>
<button disabled>提交中...</button>
<button onClick={() => send("success")}>模拟成功</button>
<button onClick={() => send("failure")}>模拟失败</button>
</>
)}
{state === "success" && <button onClick={() => send("reset")}>完成✅(重置)</button>}
{state === "error" && <button onClick={() => send("reset")}>失败❌(重置)</button>}
</div>
);
}
运行后:
- 默认状态是
idle。 - 点击后进入
loading。 - 可以选择「成功」进入
success或「失败」进入error。 - 在
success或error状态下,可以「重置」回到idle。
👉点击进入 我的网站