【问题标题】:Add tracking to a SPA向 SPA 添加跟踪
【发布时间】:2017-10-09 04:40:07
【问题描述】:
我有一个 react SPA,需要在 react 路由器加载/更改页面时添加跟踪,以便跟踪了解用户正在做的所有事情。我什至不知道从哪里开始。
我尝试在 index.html 中加载跟踪脚本,然后在 componentDidMount 函数中添加跟踪对象,但这不起作用,因为在页面加载时不会发生这种情况。
我需要做什么?
【问题讨论】:
标签:
javascript
reactjs
single-page-application
tracking
【解决方案1】:
如果你也在使用 redux:
按照基本设置指南设置react-router-redux
然后,您将能够设置一个与路由挂钩的简单中间件。像这样定义middlewares/routing.js:
// https://github.com/reactjs/react-router-redux#location_change
import { LOCATION_CHANGE } from 'react-router-redux';
export default function routeTracker(store) {
return next => action => {
if (action.type === LOCATION_CHANGE) {
// whatever action you want here.
}
next(action);
}
}
现在在创建商店的地方导入并应用此中间件
import routeTracker from '../middlewares/router';
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';
export default function createStore(initialState) {
// ...
const enhancer = compose(applyMiddleware(routeTracker));
const store = createStore(rootReducer, initialState, enhancer);
return store;
}