【问题标题】:How to track analytics events with xstate如何使用 xstate 跟踪分析事件
【发布时间】:2021-08-01 22:38:22
【问题描述】:

我在我的 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,但是没有文档,而且自述文件说我们不应该使用它^^

有没有一种方法可以在每次转换时调用一个动作而不会重复太多?

【问题讨论】:

    标签: reactjs react-native analytics xstate


    【解决方案1】:

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

    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',
            },
          }
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-18
      • 2016-02-22
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多