我在中使用xstate来管理一个相当复杂的流。我想系统地记录关于每个状态转换和状态机中发生的事件的分析事件。到目前为止,我还没有想到如何不从每个事件手动调用logEvent操作。例如,在一台比我建造的机器小得多的机器上:
const machine = createMachine({
id: 'machine',
initial: 'idle',
context: {},
states: {
idle: {
on: {
NEXT: {
target: 'green',
actions: ['logEvent'] // <-------- here
}
}
},
green: {
on: {
NEXT: {
target: 'green',
actions: ['logEvent'] // <-------- here
},
BACK: {
target: 'idle',
actions: ['logEvent'] // <-------- here
},
}
},
red: {
on: {
NEXT: {
target: 'idle',
actions: ['logEvent'] // <-------- here
},
BACK: {
target: 'green',
actions: ['logEvent'] // <-------- here
},
}
}
}
})如此多的重复:
我所读到的另一种方法是使用interpret并添加onTransition侦听器(https://xstate.js.org/docs/guides/interpretation.html#transitions)。但是,这也需要手动发送事件以使onTransition侦听器触发,因此它不是一个解决方案。
我也找到了@xstate/分析,但是没有文档,自述说我们不应该使用它^^
,是否有一种方法可以在每个过渡过程中调用一个动作,而不必重复这么多?
发布于 2021-07-01 12:30:32
你可以试着把它作为每个州的一个入口动作。
const machine = createMachine({
id: 'machine',
initial: 'idle',
context: {},
states: {
idle: {
entry: ['logEvent'],
on: {
NEXT: {
target: 'green',
}
}
},
green: {
entry: ['logEvent'],
on: {
NEXT: {
target: 'green',
},
BACK: {
target: 'idle',
},
}
},
red: {
entry: ['logEvent'],
on: {
NEXT: {
target: 'idle',
},
BACK: {
target: 'green',
},
}
}
}
})https://stackoverflow.com/questions/67488842
复制相似问题