zoukankan      html  css  js  c++  java
  • [XState] Conditionally Transition to States with Guards in XState

    Not all transitions should be taken immediately. Occasionally, we would like to conditionally take a transition. We do this through the use of "guards". A "guard" is a predicate function (a function that returns a boolean) that is set on a transition object's cond property (short for "conditional").

    When an event is sent to the machine and it encounters a transition object with a cond property set to a guard function, it will call that function with the current context and event object. If the guard returns true, the transition will be taken, otherwise, it will attempt the next transition for the event, or remain in the current state.

    The code logic is, before 'deposited' larger or equal than 100, we cannot do 'vending'. It uses 'guards' & 'cond'.

    const { Machine, interpret } = require("xstate");
    
    const vendingMachine = Machine(
      {
        id: "vendingMachine",
        initial: "idle",
        context: {
          deposited: 0
        },
        states: {
          idle: {
            on: {
              SELET_ITEM: {
                target: "vending",
                cond: "depositedEnough"
              },
              DEPOSIT_QUARTER: {
                actions: ["addQuarter"]
              }
            }
          },
          vending: {}
        }
      },
      {
        actions: {
          addQuarter: assign({
            deposited: context => context.deposited + 25
          })
        },
        guards: {
          depositedEnough: context => context.deposited >= 100
        }
      }
    );

    Before valid:

    After valid:

    vending:

  • 相关阅读:
    JAVA GUI设
    3.4 jmu-java-随机数-使用蒙特卡罗法计算圆周率的值 (10 分)
    问题:关于2.3 jmu-Java-02基本语法-03-身份证排序 (9 分)
    关于3.1 jmu-Java-03面向对象基础-01-构造函数与toString (3 分)
    linux vim文件编辑的常用命令
    linux的常用命令
    linux文件存储方式
    第一个java
    hdu 2795
    hdu 1394
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12215896.html
Copyright © 2011-2022 走看看