如何让XState状态机完成任务后返回idle初始状态?
实现方案
你有两种常用方式可以实现进入success状态后返回idle:
方式一:移除success的final类型,直接跳转回idle
如果不需要利用final状态的完成事件,最简单的方式是去掉success状态的type: 'final',直接指定跳转目标为idle,还可以按需添加收尾动作:
states: { idle: { id: 'initialState' }, waitingForA: { invoke: { /* Promise */ }, onDone: { target: 'waitingForB' }, // 修正拼写错误:wiatingForB → waitingForB onError: { actions: () => alert('获取A失败') } // 修正语法:用actions包裹执行逻辑 }, waitingForB: { invoke: { /* Promise */ }, onDone: { target: 'waitingForC', actions: assign({ bReturnCode: (context, event) => event.data }) } }, waitingForC: { invoke: { /* Promise */ }, onDone: { target: 'success', actions: assign({ cReturnCode: (context, event) => event.data }) }, onError: { // 修正语法:添加缺失的冒号 target: 'showAlert' } }, success: { entry: () => console.log('任务完成'), // 可选:添加收尾动作 always: { target: 'idle' } // 进入success后立即跳转到idle }, showAlert: { entry: () => alert('获取C失败'), always: { target: 'idle' } // 错误状态也可按需跳回idle } }
方式二:保留final类型,监听状态机完成事件
如果需要保留success的final类型(用来标记核心逻辑完成),可以在根状态监听状态机的完成事件,触发后跳转回idle:
createMachine({ id: 'dataFetchMachine', initial: 'idle', states: { idle: { id: 'initialState' }, waitingForA: { invoke: { /* Promise */ }, onDone: { target: 'waitingForB' }, onError: { actions: () => alert('获取A失败') } }, waitingForB: { invoke: { /* Promise */ }, onDone: { target: 'waitingForC', actions: assign({ bReturnCode: (context, event) => event.data }) } }, waitingForC: { invoke: { /* Promise */ }, onDone: { target: 'success', actions: assign({ cReturnCode: (context, event) => event.data }) }, onError: { target: 'showAlert' } }, success: { type: 'final' }, showAlert: { entry: () => alert('获取C失败'), always: { target: 'idle' } } }, // 根状态监听完成事件,跳转回idle on: { 'done.state.dataFetchMachine': { target: 'idle', actions: () => console.log('任务彻底完成,返回初始状态') } } })
额外提示
- 已修正你原代码中的拼写错误(
wiatingForB)和语法错误(onError缺冒号、错误处理逻辑未用actions包裹) - 如果需要在返回idle前重置上下文数据,可以在跳转动作中添加
assign,比如actions: assign({ bReturnCode: null, cReturnCode: null })
内容的提问来源于stack exchange,提问作者SoftwareDveloper
相关产品推荐
相关产品推荐

