[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine相关的知识,希望对你有一定的参考价值。

We can invoke a callback as a service when we enter a state in XState. This gives us the ability to trigger various functionality by responding to events sent to the service, and allows us to send events back to the parent machine.

We do this by writing a "callback handler" and setting it as the src of our invoked service. A callback handler is a function that receives the current context and the event object that triggered the invocation. This function returns another function that receives two functions as arguments. A callback function to send events to the parent machine, and an onEvent function for the handler to respond to events sent to the handler.

The way events are sent to the callback handler is by utilizing the options argument of the send action creator. We identify where we send events to using the to property, and setting the value to the id of our service.

 

const handlerEchoCallback = (context, event) => {
  return (callback, onReceive) => {
    onReceive(e => {
      if (e.type === FOO) {
       callback(ECHO); // call the ‘ECHO‘ action
      }
    })
  }
}

const callbackMachine = Machine({
  id: callbackMachine,
  initial: listening,
  states: {
    listening: {
      invoke: {
        src: handlerEchoCallback,
        id: handlerEchoCallback
      },
      on: {
        SPEAK: {
          actions: send(FOO, {
            to: handlerEchoCallback
          })
        },
        ECHO: {
          actions: (context, event) => {
            console.log(echo, context, event);
          }
        }
      }
    }
  }
})

 

以上是关于[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine的主要内容,如果未能解决你的问题,请参考以下文章

XState:在没有中间状态的情况下链接多个 Promise

XState 不会停留在空闲状态

[XState] Track Infinite States with with XState Context

[XState] Simplify State Explosion in XState through Hierarchical States

[XState] Use Activities in XState to Run Ongoing Side Effects

[XState] Invoking a Promise for Asynchronous State Transitions in XState