能否通过父机"spawn"函数或"useActor" Hook为Spawned Machine传递"guards"、"delays"配置项?
为Spawned Machine传递配置项的方法
通过spawn函数传递配置
可以直接通过spawn函数的第二个参数,为子状态机传递guards、delays这类配置项。调用spawn时,将自定义配置作为选项对象传入即可,传入的配置会合并或覆盖子状态机的默认配置:
// 定义子状态机 const childMachine = createMachine({ states: { // ... 子机状态定义 }, // 子机默认配置 guards: { isAuthorized: () => false }, delays: { timeout: 1000 } }); // 父状态机中使用spawn注入自定义配置 const parentMachine = createMachine({ context: { user: { isAdmin: true } }, entry: [ assign({ childActor: (ctx) => spawn(childMachine, { // 覆盖或新增守卫配置 guards: { isAuthorized: () => ctx.user.isAdmin }, // 覆盖延迟配置 delays: { timeout: 3000 } }) }) ] });
通过useActor Hook传递配置
useActor的作用是获取已创建的actor的状态、发送事件,它无法直接传递机器配置项——因为配置项是在actor被spawn实例化时就确定的。如果需要给子actor配置自定义规则,必须在spawn阶段完成配置注入,之后再用useActor操作这个已配置好的actor:
import { useMachine, useActor } from '@xstate/react'; function ParentComponent() { const [parentState] = useMachine(parentMachine); // 获取已配置完成的子actor const [childState, sendToChild] = useActor(parentState.context.childActor); return ( /* 组件内容 */ ); }
若需要动态更新配置,常规做法是销毁原actor,重新spawn一个带有新配置的实例。
内容的提问来源于stack exchange,提问作者DiniMad
相关产品推荐
相关产品推荐

