阅读 228

Taro小程序关于数据埋点的处理方式

场景:当数据接口需要记录浏览文章的进入时间,离开时间以及总共停留时间时,我们会在进入该页面的时候记录开始时间,离开页面时记录离开时间并在离开的时候调用后端接口。

原本是简单的在useEffect中简单return函数上调用,在正常流程进入点击返回时可以调用成功,但是当该文章被分享的时候点击进入没有返回健,左上角只有home键,此时会发现部分取于store或者文章详情的数据会丢失。 解决方法:当不管是分享进入还是自行进入时,都将数据保存至本地

import { useStore, observer } from '@store'; import dayjs from 'dayjs'; import MD5 from 'js-md5'; import ajax from '@server'; const { CommonStore } = useStore(); const { appStartTime, initTime } = CommonStore; const setParams = () => { let newInfo = storage.getLocalStorage('newInfo'); let newDetail = storage.getLocalStorage('newDetail'); if (newInfo && newDetail) {   newInfo = JSON.parse(newInfo);   newDetail = JSON.parse(newDetail);   const { id, userId, headCompany, branchFirst, branchSecond, department } = newInfo;   const { name, code } = newDetail;   const traceId = userId + appStartTime.valueOf();   const viewQuery: any = {     headCompany: headCompany,     investmentAdvisorId: id,     branchFirst,     branchSecond,     department,     enterTime: appStartTime,     traceId: MD5(traceId.toString()).substring(8, 24).toUpperCase(),     productId: myparams[0],     productName: name, //产品名     productCode: code, //产品代码     title: name,     productType: 2,   };   return viewQuery; } return {}; }; //用户产品<浏览>数据 保存浏览数据  const postProduceRecord = () => {     const viewQuery = setParams();     viewQuery.duration = dayjs().diff(appStartTime, 'second');     viewQuery.leaveTime = dayjs();     ajax.postProduceRecord(viewQuery).then((res) => { });   }; //进入页面时初始化时间,获取详情 useEffect(() => {   initTime();   getFinacialDetail(); }, []); //获取到详情的时候存本地 useEffect(() => {     if (detail?.name && adviserInfo.name) {         const newInfo = JSON.stringify(adviserInfo);         storage.setLocalStorage('newInfo', newInfo);         const newDetail = JSON.stringify(detail);         storage.setLocalStorage('newDetail', newDetail);     } }, [detail, adviserInfo]); //离开页面时调用接口 useEffect(() => { return () => {   postProductRecord(); }; }, []); 复制代码

//common.ts import { observable, action } from 'mobx'; import dayjs from 'dayjs'; class CommonStore {     @observable appStartTime = dayjs();     @action.bound     initTime() {         this.appStartTime = dayjs();     } } export default new CommonStore(); export interface ICommonStore extends CommonStore { }


作者:廖锦玉
链接:https://juejin.cn/post/7038212238833877000

 伪原创工具 SEO网站优化  https://www.237it.com/ 


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐