使用 XState,如何访问操作中当前状态的名称?

Sig*_*tic 5 javascript xstate

我正在学习 XState,并希望在机器中包含一个仅将当前状态记录到控制台的操作。

像这样定义一个简单的示例机器,我将如何去做呢?另请注意代码中注释中的问题。

import { createMachine, interpret } from "xstate"

const sm = createMachine({
    initial: 'foo',
    states: {
        foo: {
            entry: 'logState', // Can I only reference an action by string?
                               // Or can I add arguments here somehow?
            on: {
                TOGGLE: {target: 'bar'}
            }
        },
        bar: {
            entry: 'logState',
            on: {
                TOGGLE: {target: 'foo'}
            }
        }
    }
},
{
    actions: {
        logState(/* What arguments can go here? */) => {
            // What do I do here?
        }
    }
});

Run Code Online (Sandbox Code Playgroud)

我知道操作是用contextevent作为参数调用的,但我没有找到从其中任何一个获取当前状态的方法。我在这里错过了什么吗?

guo*_*owy 0

对于像您这样的简单用例,您可以尝试记录转换时的状态。

let currentState;
const service = interpret(machine).onTransition(state => {
   if (state.value != currentState) {
       // TODO: terminate timer if any and start a new one
      currentState = state.value;
   }
});
Run Code Online (Sandbox Code Playgroud)

然后在您的行动中使用该价值。

在这里查看更多信息:https ://github.com/statelyai/xstate/discussions/1294