我很难让跟踪链接在反应中按预期工作。我注意到的主要警告是重复的事件可能会突然发送到混合面板。我使用了一个稍微修改过的@Kyle 版本来解决我的问题。此外,这properties
可能是 mixpanel API 支持的功能。
// mixpanelSetup.js
import md5 from "md5";
const setup = () => {
mixpanel.init(TOKEN);
// Sets ensure unique items
mixpanel.delegated_links = new Set();
mixpanel.delegate_links = (parent, selector, eventName, eventProperties, {ignoreUrl=false}) => {
// Hash by whatever thing(s) the use case considers 'unique' (e.g md5(`${selector}__${eventName}`))
const linkHash = md5(selector);
parent = parent || document.body;
parent = $(parent);
// Do not add additional trackers for an already tracked event.
if (mixpanel.delegated_links.has(linkHash)) {
return;
}
mixpanel.delegated_links.add(linkHash);
parent.on("click", selector, (event) => {
const newTab = event.which === 2 || event.metaKey || event.target.target === "_blank";
if (typeof eventProperties === "function") {
eventProperties = eventProperties(event.target) || {};
}
eventProperties.url = event.target.href;
// In case we don't want the url on the properties.
if (ignoreUrl) {
delete eventProperties.url;
}
const callback = () => {
if (newTab) {
return;
}
window.location = event.target.href;
};
if (!newTab) {
event.preventDefault();
setTimeout(callback, 300);
}
console.debug("Tracking link click!");
mixpanel.track(eventName, eventProperties, callback);
});
};
}
并可用作:
// MyComponent.jsx
import React, { useEffect } from "react";
import { Link, useLocation } from "@reach/router";
const MyComponent = ({ moduleName, key, ...props }) => {
const id = `#${id}__${moduleName}`;
useEffect(() => {
mixpanel.delegate_links(document.parent, id, event => {
return {
module: event.id.split("__").pop(),
...props.otherPropsToTrack
};
})
}, [])
return <>
<Link {...props} to="/some/path" id={id}>My Page</Link>
</>
}