将事件发送到 XState 中的子服务数组

Send event to array of child services in XState

我有一个场景,我有一台父机器和几台可以从父机器生成的子机器。

当前设置如下所示:

const parentMachine = Machine({
  context: {
    children: [] //can contain any number of child services
  },
  ...
  on: {
    ADD_CHILD: {
       actions: assign({
         children: (ctx, e) => {
           return [
             ...ctx.children,
             {
               ref: spawn(childMachine)
             },
           ];
         },
      }),
    },
    UPDATE_CHILDREN: {
      actions: ??? //need to somehow loop through children and send the UPDATE event to each service
    }
  }
});

当父机器收到"UPDATE_CHILDREN"事件时,我想更新每个子服务。我知道您可以通过将数组传递给 send 来发送批处理事件,但我希望每个事件也被发送到不同的服务。我只见过一次将它们发送到单个服务的示例。我已经尝试了几件事,包括以下内容:

UPDATE_CHILDREN: {
  actions: ctx => ctx.children.forEach(c => send("UPDATE", { to: () => c.ref }) //doesn't send 
}

我是不是遗漏了什么明显的东西?这可能吗?

了解这在 XState 中应该如何工作。

对 children 的引用已经被存储,所以我们基本上可以直接向它们发送事件而无需使用 "to" 属性:

actions: ctx => ctx.children.forEach(c => c.ref.send("UPDATE"))

啊,我遇到了和你一模一样的问题!

事实证明,如果您给 actions 一个函数,它会假定该函数是实际操作,而不是 returns 操作的函数。

如果你想根据上下文生成你的动作,你需要使用a pure action:

import { actions } from 'xstate';

const { pure } = actions;

...

    actions: pure((context, event) =>
      context.myActors.map((myActor) =>
        send('SOME_EVENT', { to: myActor })
      )
    ),

这是一个棘手的错误,因为您没有得到关于您做错事的反馈..