0

我有以下代码,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下一个状态没有运行,但如果cond: () => test === true它运行。

是代码有错误,还是mu的理解cond有误?

4

1 回答 1

0

你的理解cond不太正确。只有当守卫(cond表达式)通过(即计算结果为true)时才会进行转换。

过渡意味着:

  • 转换到target状态(如果有)
  • 执行actions(如果有)

除非采取行动,否则不会在转换上执行操作,并且由于守卫正在阻止执行转换,因此test = false不会执行设置的操作。

另外,请防止外部突变(test变量存在于机器之外)。它使状态机的确定性降低,这违背了使用状态机的目的。

于 2019-10-12T13:33:23.273 回答