码迷,mamicode.com
首页 > 其他好文 > 详细

[XState] Simplify State Explosion in XState through Hierarchical States

时间:2020-01-20 00:06:47      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:alt   instead   bsp   evel   idt   can   src   nbsp   arc   

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

标签:alt   instead   bsp   evel   idt   can   src   nbsp   arc   

原文地址:https://www.cnblogs.com/Answer1215/p/12215942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!