StateMachine
中的states
属性是状态机的状态集合,即各个状态的列表。
const stateMachine = new StateMachine({
states: {
stateName1: stateConfig1,
stateName2: stateConfig2,
...
}
});
stateName
:状态名称,是一个字符串。
stateConfig
:状态配置,是一个对象,包含以下属性:
onEnter
:进入该状态时需要执行的函数。onLeave
:离开该状态时需要执行的函数。transitions
:该状态下所有可能的转移。以下示例定义了一个有限状态机(Finite State Machine),其中包含三个状态:idle
、fetching
和error
。其中,idle
状态表示空闲,fetching
状态表示正在抓取数据,error
状态表示发生错误。
const stateMachine = new StateMachine({
states: {
idle: {
onEnter: function() {
console.log('进入 idle 状态');
},
transitions: {
fetching: 'fetching',
error: 'error'
}
},
fetching: {
onEnter: function() {
console.log('进入 fetching 状态');
},
transitions: {
idle: 'idle',
error: 'error'
}
},
error: {
onEnter: function() {
console.log('进入 error 状态');
},
transitions: {
idle: 'idle',
fetching: 'fetching'
}
}
}
});
stateMachine.transition('fetching');
// 进入 fetching 状态
stateMachine.transition('error');
// 进入 error 状态
在上述示例中,states
属性中定义了三个状态,并为每个状态指定了onEnter
函数和transitions
属性,表示每个状态下可能的转移。在转换状态时,transition
方法会自动执行相应的onEnter
方法。