1

我在我的 React Native 应用程序中使用 xstate 来管理一个相当复杂的流程。我想系统地记录状态机中发生的每个状态转换和事件的分析事件。到目前为止,我还没有想出如何在不手动调用logEvent每个事件的动作的情况下做到这一点。例如,在一台比我构建的机器小得多的机器上:

const machine = createMachine({
  id: 'machine',
  initial: 'idle',
  context: {},
  states: {
    idle: {
      on: {
        NEXT: {
          target: 'green',
          actions: ['logEvent'] // <-------- here
        }
      }
    },
    green: {
      on: {
        NEXT: {
          target: 'green',
          actions: ['logEvent'] // <-------- here
        },
        BACK: {
          target: 'idle',
          actions: ['logEvent'] // <-------- here
        },
      }
    },
    red: {
      on: {
        NEXT: {
          target: 'idle',
          actions: ['logEvent'] // <-------- here
        },
        BACK: {
          target: 'green',
          actions: ['logEvent'] // <-------- here
        },
      }
    }
  }
})

这么多重复:(

我读到的另一种方法是使用interpret和添加一个onTransition监听器(https://xstate.js.org/docs/guides/interpretation.html#transitions)。但是,这还需要手动发送事件以触发 onTransition 侦听器,因此它不是 imo 的解决方案。

我还找到了@xstate/analytics,但是没有文档,而且自述文件说我们不应该使用它^^

有没有办法在每次转换时调用一个动作而不会重复我自己?

4

1 回答 1

0

您可以尝试将其作为每个状态的入口操作。

const machine = createMachine({
  id: 'machine',
  initial: 'idle',
  context: {},
  states: {
    idle: {
      entry: ['logEvent'],
      on: {
        NEXT: {
          target: 'green',
        }
      }
    },
    green: {
      entry: ['logEvent'],
      on: {
        NEXT: {
          target: 'green',
        },
        BACK: {
          target: 'idle',
        },
      }
    },
    red: {
      entry: ['logEvent'],
      on: {
        NEXT: {
          target: 'idle',
        },
        BACK: {
          target: 'green',
        },
      }
    }
  }
})
于 2021-07-01T12:30:32.660 回答