[XState] Simplify State Explosion in XState through Hierarchical States

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[XState] Simplify State Explosion in XState through Hierarchical States相关的知识,希望对你有一定的参考价值。

As our state machines grow more complex, we might find ourselves in a situation where a state should only exist if the machine is already in another state. To do this, we can use hierarchical states.

Instead of attempting to define all the states of a machine at a top level, we can nest states that should only be available as children of a parent state. These substates are written exactly like the states of the top level of a machine: with an initial property, and the states of the nested state graph.

Using hierarchical states is a great way to avoid needing to check for booleans in an application. If a state can only exist when another state exists, consider if the one isn‘t in fact a child of the other.

 

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

const doorMachine = Machine({
  id: "door",
  initial: "locked",
  states: {
    unlocked: {
      initial: "closed",
      states: {
        open: {
          on: {
            CLOSED: "closed",
            LOCKED: "#lockedId"
          }
        },
        closed: {
          on: { OPEN: "open" }
        }
      }
    },
    locked: {
      id: "lockedId",
      on: { UNLOCKED: "unlocked" }
    }
  }
});

技术图片

 

以上是关于[XState] Simplify State Explosion in XState through Hierarchical States的主要内容,如果未能解决你的问题,请参考以下文章

[XState] History state

在 XState FSM 中使用外部数据

XState:等待调用函数的响应

如何在 xstate 中重用状态转换?

redux 和状态机(例如 xstate)之间的实际区别是啥?

XState 不会停留在空闲状态