有限状态机
有限状态机
有限状态机
一个正式的有限状态机包含五个部分:
- 有限数量的状态
(state) - 有限数量的事件
(event) - 一个初始状态
(initial state) - 一个转换函式
(transition function) ,传入当前的状态及事件时会返回下一个状态 - 具有
0 至n 个最终状态(final state)
需要强调的是这裡的 状态
建立第一个Machine
import { Machine } from "xstate";
const lightMachine = Machine({
states: {
red: {},
green: {},
yellow: {},
},
});
首先我们需要订定
import { Machine } from "xstate";
const lightMachine = Machine({
states: {
red: {},
green: {},
yellow: {},
},
});
接下来我们要定义初始状态,假如说我们希望一开始是红灯,那就给
import { Machine } from "xstate";
const lightMachine = Machine({
initial: "red",
states: {
red: {},
green: {},
yellow: {},
},
});
import { Machine } from "xstate";
const lightMachine = Machine({
initial: "red",
states: {
red: {
on: {
CLICK: "green",
},
},
green: {
on: {
CLICK: "yellow",
},
},
yellow: {
on: {
CLICK: "red",
},
},
},
});
我们在每个状态下加入
import { Machine } from "xstate";
const lightMachine = Machine({
//...
});
const state0 = lightMachine.initialState;
console.log(state0);
const state1 = lightMachine.transition(state0, "CLICK");
console.log(state1);
const state2 = lightMachine.transition(state1, "CLICK");
console.log(state2);
const state3 = lightMachine.transition(state2, "CLICK");
console.log(state3);
这个回传的
- value
- matches(parentStateValue)
- nextEvents
import { Machine } from "xstate";
const lightMachine = Machine({
//...
});
const state0 = lightMachine.initialState;
console.log(state0.value); // 'red'
const state1 = lightMachine.transition(state0, "CLICK");
console.log(state1.value); // 'green'
state0.matches("red"); // true
state0.matches("yellow"); // false
state0.matches("green"); // false
import { Machine } from "xstate";
const lightMachine = Machine({
//...
});
const state0 = lightMachine.initialState;
console.log(state0.nextEvents); // 'CLICK'
这样一来我们就完成了一个简单的
Interpret
import { Machine, interpret } from "xstate";
const lightMachine = Machine({
//...
});
const service = interpret(lightMachine);
// 启动 service
service.start();
// Send events
service.send("CLICK");
// 停止 service 当你不在使用它
service.stop();
import { Machine, interpret } from "xstate";
const lightMachine = Machine({
//...
});
const service = interpret(lightMachine);
// 启动 service
service.start();
console.log(service.state.value); // 'red'
service.send("CLICK"); // Send events
console.log(service.state.value); // 'green'
// 停止 service 当你不在使用它
service.stop();
这样一来我们就可以很简单的透过