[XState] Use Internal Transitions in XState to Avoid State Exit and Re-Entry

Transitions come in two varieties: "external" and "internal". By default, a transition is considered external. This means that a transition will exit the current state node, and enter the next state node (even if that state node is the state the machine is currently in). This exit/enter loop will trigger any actions that are set on the exit and entry properties.

A transition can be set to internal, either through setting a . (dot) in front of the state node name (as we do in this lesson), or through setting the property internal to true on the transition object.

When a transition is internal, it will not exit and enter the state node, which means that the actions in the exit/transition/entry loop will not be called.

const { Machine } = require("xstate");

const idleMachine = Machine(
  {
    id: "idle",
    initial: "idle",
    states: {
      idle: {
        entry: ["logEntry"],
        exit: ["logExit"]
      }
    },
    on: {
      DO_NOTHING: ".idle" // add '.' to point it to itself, without call exit and entry actions
    }
  },
  {
    actions: {
      logEntry: () => {
        console.log("entered");
      },
      logExit: () => {
        console.log("exited");
      }
    }
  }
);

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12215442.html