【问题标题】:Is there a way to have guarded transitions within Hierarchical State Nodes in xState有没有办法在 xState 的分层状态节点中进行保护转换
【发布时间】:2020-05-14 04:58:22
【问题描述】:

正如标题所暗示的,我有一个受保护的转换,我想处于分层状态节点中,但是 xState 似乎无法读取保护的属性并返回“TypeError: Cannot read property 'propertyName' of undefined" error

有没有办法在 xState 中做到这一点,或者在这种情况下我应该在没有分层状态节点的情况下继续

【问题讨论】:

标签: state-machine xstate


【解决方案1】:

我使用文档中的分层状态机example 尝试对此进行建模,并在示例的末尾添加以下内容:

    on: {
      POWER_OUTAGE: '.red.blinking',
      POWER_RESTORED: '.red',
      POWER_TEST: {
        target: '.red.stop',
        cond: {
          type: 'test'
        }
      }
    }
  },{
    guards: {
      test: () => true
    }
  });

这似乎按预期工作,您可以在可视化器here 中尝试这台机器和守卫示例

您可以翻转测试守卫中的布尔值以使其正常工作/不工作。

这里是示例的完整代码供参考:

const pedestrianStates = {
    initial: 'walk',
    states: {
      walk: {
        on: {
          PED_COUNTDOWN: 'wait'
        }
      },
      wait: {
        on: {
          PED_COUNTDOWN: 'stop'
        }
      },
      stop: {},
      blinking: {}
    }
  };

  const lightMachine = Machine({
    key: 'light',
    initial: 'green',
    states: {
      green: {
        on: {
          TIMER: 'yellow'
        }
      },
      yellow: {
        on: {
          TIMER: 'red'
        }
      },
      red: {
        on: {
          TIMER: {
            target: 'green',
            cond: {
              type: 'searchValid'
            }
          }
        },
        ...pedestrianStates
      }
    },
    on: {
      POWER_OUTAGE: '.red.blinking',
      POWER_RESTORED: '.red',
      POWER_TEST: {
        target: '.red.stop',
        cond: {
          type: 'test'
        }
      }
    }
  },{
    guards: {
      test: () => true
    }
  });

【讨论】:

  • 非常感谢您的回答。不幸的是,我试图在分层状态中设置警卫。而你的例子外面有警卫。我应该更具描述性。对此感到抱歉。
【解决方案2】:

没错,我遇到的问题是我将上下文分配给了我的分层状态机而不是父计算机,因此警卫无法访问它。将上下文移动到父计算机已解决问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2011-01-09
    • 2021-04-28
    • 1970-01-01
    • 2011-01-06
    • 2020-08-19
    • 2020-03-14
    • 2020-04-15
    相关资源
    最近更新 更多