检查 xstate 机器定义中的 cond 语句
checking the cond statement in xstate machine defenition
我有以下代码,start
状态的条件给我带来了麻烦。
const machine = require('xstate');
let test = true;
// Stateless machine definition
// machine.transition(...) is a pure function used by the interpreter.
const helloMachine = machine.Machine({
id: 'hello',
initial: 'start',
states: {
start: {
on: {
STOP: {
target: 'stop',
actions: ['hi'],
// ! something is wrong with cond structure
cond: () => test === false // returns either true or false, which signifies whether the transition should be allowed to take place
}
}
},
stop: {
entry: ['hello'], // The action(s) to be executed upon entering the state node.
type: 'final'
}
}
}, {
actions: {
hello: (context, event) => {
const hello = 'Hello World';
console.log(hello)
},
hi: () => {
test = false;
console.log(`${test} -> ${typeof(test)}`);
}
}
})
// Machine instance with internal state
const helloService = machine.interpret(helloMachine)
helloService.start();
helloService.send('STOP');
据我所知,如果测试为假,它应该进入下一个状态。最初test = true
,在hi
动作中我切换为false,然后检查条件,如果cond: () => test === false
下一个状态不运行,但如果[=15] =] 它 运行s.
是代码有误,还是mu理解cond
有误?
您对cond
的理解不太正确。仅当守卫(cond
表达式)通过(即评估为 true
)时才进行转换。
进行过渡意味着:
- 过渡到
target
状态(如果有)
- 正在执行
actions
(如果有的话)
除非发生转换,否则不会执行操作,并且由于守卫阻止发生转换,因此不会执行设置 test = false
的操作。
此外,请防止外部突变(test
变量存在于机器之外)。它使状态机的确定性降低,这违背了使用状态机的目的。
我有以下代码,start
状态的条件给我带来了麻烦。
const machine = require('xstate');
let test = true;
// Stateless machine definition
// machine.transition(...) is a pure function used by the interpreter.
const helloMachine = machine.Machine({
id: 'hello',
initial: 'start',
states: {
start: {
on: {
STOP: {
target: 'stop',
actions: ['hi'],
// ! something is wrong with cond structure
cond: () => test === false // returns either true or false, which signifies whether the transition should be allowed to take place
}
}
},
stop: {
entry: ['hello'], // The action(s) to be executed upon entering the state node.
type: 'final'
}
}
}, {
actions: {
hello: (context, event) => {
const hello = 'Hello World';
console.log(hello)
},
hi: () => {
test = false;
console.log(`${test} -> ${typeof(test)}`);
}
}
})
// Machine instance with internal state
const helloService = machine.interpret(helloMachine)
helloService.start();
helloService.send('STOP');
据我所知,如果测试为假,它应该进入下一个状态。最初test = true
,在hi
动作中我切换为false,然后检查条件,如果cond: () => test === false
下一个状态不运行,但如果[=15] =] 它 运行s.
是代码有误,还是mu理解cond
有误?
您对cond
的理解不太正确。仅当守卫(cond
表达式)通过(即评估为 true
)时才进行转换。
进行过渡意味着:
- 过渡到
target
状态(如果有) - 正在执行
actions
(如果有的话)
除非发生转换,否则不会执行操作,并且由于守卫阻止发生转换,因此不会执行设置 test = false
的操作。
此外,请防止外部突变(test
变量存在于机器之外)。它使状态机的确定性降低,这违背了使用状态机的目的。