我正在学习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?
}
}
});我知道以context和event作为参数调用操作,但我看不到从这两个参数中获取当前状态的方法。我是不是漏掉了什么?
发布于 2022-07-20 21:07:13
对于像您这样的简单用例,您可以尝试在转换时记录状态。
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;
}
});然后在您的操作中使用该值。
请参阅这里的更多内容:https://github.com/statelyai/xstate/discussions/1294
发布于 2022-07-21 09:50:24
操作接收三个参数- context、event和meta。meta具有属性state,该属性为当前状态。
import { createMachine } from "xstate";
let metaDemo = createMachine(
{
id: "meta-demo",
initial: "ping",
states: {
ping: {
entry: ["logStateValues"],
after: { TIMEOUT: "pong" },
},
pong: {
entry: ["logStateValues"],
after: { TIMEOUT: "ping" },
},
},
},
{
delays: {
TIMEOUT: 3000,
},
actions: {
logStateValues(ctx, event, meta) {
if (meta.state.matches("ping")) {
console.log("It's PING!");
} else if (meta.state.matches("pong")) {
console.log("And now it's PONG");
} else {
console.log(
`This is not supposed to happen. State is: ${meta.state
.toStrings()
.join(".")}`
);
}
},
},
}
);https://stackoverflow.com/questions/72090829
复制相似问题