[XState] Multiple Simultaneous States with Parallel States

Posted answer1215

tags:

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

Can you walk and talk at the same time? If so, you‘ve experienced what it‘s like to be in two states at the same time. Hopefully, those two states have no influence on the other. Whether or not you talk, you can walk, and vice versa. States that occur concurrently and have no affect on the other are known as "parallel states".

Parallel states happen simultaneously. The machine is in all of the parallel states at the same time. To create a parallel state node, we set the type to ‘parallel‘ and then remove the initial state. There‘s no need for an initial property when you‘re in all the child states at the same time.

 

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

const spaceHeaterMachine = Machine({
  id: "spaceHeater",
  initial: "poweredOff",
  states: {
    poweredOff: {
      on: { TOGGLE_POWER: "poweredOn" }
    },
    poweredOn: {
      on: { TOGGLE_POWER: "poweredOff" },
      type: "parallel", // mark parallel
      states: {
        heated: {
          initial: "lowHeat",
          states: {
            lowHeat: {
              on: { TOGGLE_HEAT: "highHeat" }
            },
            highHeat: {
              on: { TOGGLE_HEAT: "lowHeat" }
            }
          }
        },
        oscillation: {
          initial: "disabled",
          states: {
            disabled: {
              on: { TOGGLE_OSC: "enabled" }
            },
            enabled: {
              on: { TOGGLE_OSC: "disabled" }
            }
          }
        }
      }
    }
  }
});

技术图片

以上是关于[XState] Multiple Simultaneous States with Parallel States的主要内容,如果未能解决你的问题,请参考以下文章

[XState] Track Infinite States with with XState Context

[XState] Invoke Child XState Machines from a Parent Machine

[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

XState:等待调用函数的响应