Redux Beacon 是 Redux和 ngrx的分析中间软件,允许您在发送时跟踪操作,并将其发送给任何数量的分析提供商。
在本文中,我们将使用 Redux Beacon,Google Analytics,并在单页的React应用程序中跟踪页面视图和事件。
设置
请注意,您首先需要添加到您的网站的 Google Analytics 帐户和 Analytics.js。
要为 Google Analytics 安装 Redux Beacon,请使用 npm 或 Yarn 并安装redux-beacon
和@redux-beacon/google-analytics
。
1$ npm install —save redux-beacon @redux-beacon/google-analytics
2
3# or, using Yarn:
4$ yarn add redux-beacon @redux-beacon/google-analytics
<$>[警告]在使用 Google Analytics 工作和测试时,将您的网站列入您可能安装的任何广告/跟踪阻止器中。
定义要追踪什么
我们将涵盖页面视图和事件跟踪,但对于Redux Beacon的Google Analytics插件也支持跟踪时间、电子商务、社交互动和错误。
Redux Beacon 通过检查您发送的每个操作,并将其类型与事件地图中的操作类型进行比较。
1const eventsMap = {
2 MY_ACTION_ONE: someTrackingFn(…),
3 MY_ACTION_TWO: someOtherTrackingFn(…)
4 …
5}
当MY_ACTION_ONE
发送时,将呼叫someTrackingFn
。
页面视图
使用 Redux Beacon 跟踪页面视图意味着将您的动作类型绘制到页面视图函数,以便更改路线。
1import { LOCATION_CHANGE } from ‘react-router-redux’;
2
3const eventsMap = {
4 [LOCATION_CHANGE]: ourPageViewFn()
5};
每次发送LOCATION_CHANGE
时,我们的页面视图函数将被调用,我们可以使用此函数从操作中提取我们想要追踪的数据。
页面视图功能是什么样子? 完整示例:
1import { LOCATION_CHANGE } from ‘react-router-redux’;
2import { trackPageView } from '@redux-beacon/google-analytics';
3
4const eventsMap = {
5 [LOCATION_CHANGE]: trackPageView(action => ({
6 page: action.payload.pathname,
7 title: "My amazing page title"
8 }))
9};
可选情况下,转移到trackPageView
函数的箭头函数也可能需要两个额外的参数,即prevState
和nextState
。
1trackPageView((action, prevState, nextState) => { … })
事件
在谷歌分析领域,事件是您网站/应用程序上的可追踪的用户互动,点击按钮、下载内容和点击广告都是可追踪的事件。
让我们看看这个跟踪定义是什么样子:
1const eventsMap = {
2 "DOWNLOAD_CLICKED": trackEvent(action => ({
3 category: "VideoFile",
4 action: "download",
5 value: action.videoId
6 }))
7};
在这种情况下,当用户点击下载按钮时,将跟踪videoId
,以及类别和操作。
请注意,值
必须是整数。
最后步骤
在 Redux Beacon 能够读取您的操作之前,必须将事件定义转换为CreateMiddleware
函数的中间件,并在创建 redux 商店时转移到applyMiddleware
函数:
1import { createStore, applyMiddleware } from 'redux';
2import { createMiddleware } from ‘redux-beacon’;
3import { LOCATION_CHANGE } from ‘react-router-redux’;
4import GoogleAnalytics, { trackPageView, trackEvent }
5 from '@redux-beacon/google-analytics';
6
7const ga = GoogleAnalytics();
8const eventsMap = {
9 [LOCATION_CHANGE]: trackPageView(/* ... */),
10 "DOWNLOAD_CLICKED": trackEvent(/* ... */)
11};
12const middleware = createMiddleware(eventsMap, ga)
13
14const myReducer = (state, action) => { ... }
15const myInitialState = {}
16const store = createStore(myReducer, myInitialState,
17 applyMiddleware(middleware));
现在我们的 redux 行动可以由 Google Analytics 跟踪! 您可以在浏览器的检查工具上打开网络选项卡,以便看到它的魔法。
回复一下:
- 在您的网站上安装 Redux Beacon 和 Google Analytics,并记住在您的浏览器上禁用广告/跟踪阻止
- 定义您的事件地图,哪些地图将行动减少到跟踪功能
- 将此事件地图转换为中间软件并将其传输到您的 redux 商店
如果一棵树落在森林里,而谷歌没有跟踪它,它会发出声音吗?