Dittofeed移动端:React Native集成
·
Dittofeed移动端:React Native集成
概述
Dittofeed作为开源客户互动平台,提供了强大的React Native SDK,让开发者能够轻松在移动应用中集成用户行为追踪和消息推送功能。本文将详细介绍如何在React Native应用中集成Dittofeed SDK,实现用户行为追踪、用户识别和移动推送通知功能。
核心功能特性
🎯 用户行为追踪
- 事件追踪:记录用户在应用中的关键行为
- 屏幕浏览:追踪用户访问的各个页面/屏幕
- 用户属性管理:存储和管理用户特征信息
📱 移动推送支持
- 原生推送通知:支持iOS和Android平台
- 实时消息传递:基于用户行为的自动化消息触发
- 多渠道集成:与邮件、SMS等其他渠道协同工作
🔄 数据同步
- 异步事件提交:高性能的事件收集机制
- 批量处理:优化网络请求,减少资源消耗
- 数据持久化:离线情况下数据自动缓存
安装与配置
环境要求
# React Native版本要求
react-native >= 0.60.0
# 平台支持
iOS >= 12.0
Android API Level >= 21
安装SDK
# 使用Yarn安装
yarn add @dittofeed/sdk-react-native
# 使用NPM安装
npm install --save @dittofeed/sdk-react-native
获取Write Key
在集成之前,需要从Dittofeed控制台获取Write Key:
- 登录Dittofeed控制台
- 进入设置页面
- 复制API密钥部分的Write Key
基础集成示例
初始化配置
import React, { useEffect } from 'react';
import { DittofeedSdk } from '@dittofeed/sdk-react-native';
const App = () => {
useEffect(() => {
const initializeDittofeed = async () => {
try {
// 初始化SDK
await DittofeedSdk.init({
writeKey: 'Basic your-write-key-here', // 替换为实际的Write Key
// 可选配置
flushInterval: 30000, // 自动刷新间隔(毫秒)
maxBatchSize: 20, // 最大批量大小
});
console.log('Dittofeed SDK initialized successfully');
} catch (error) {
console.error('Failed to initialize Dittofeed SDK:', error);
}
};
initializeDittofeed();
}, []);
return (
// 你的应用组件
);
};
export default App;
核心API使用
用户识别(Identify)
// 用户登录或注册时调用
const identifyUser = (userId, userProperties) => {
DittofeedSdk.identify({
userId: userId,
traits: {
email: userProperties.email,
firstName: userProperties.firstName,
lastName: userProperties.lastName,
phone: userProperties.phone,
createdAt: new Date().toISOString(),
// 自定义属性
subscriptionType: 'premium',
lastLogin: new Date().toISOString(),
},
});
};
// 示例调用
identifyUser('user_123', {
email: 'john@example.com',
firstName: 'John',
lastName: 'Doe',
phone: '+1234567890'
});
事件追踪(Track)
// 产品购买事件
const trackPurchase = (userId, product, amount) => {
DittofeedSdk.track({
userId: userId,
event: 'Product Purchased',
properties: {
productId: product.id,
productName: product.name,
category: product.category,
price: product.price,
quantity: product.quantity,
totalAmount: amount,
currency: 'USD',
purchaseDate: new Date().toISOString(),
},
});
};
// 应用内行为事件
const trackAppAction = (userId, action, metadata = {}) => {
DittofeedSdk.track({
userId: userId,
event: action,
properties: {
...metadata,
timestamp: new Date().toISOString(),
platform: Platform.OS, // iOS或Android
},
});
};
屏幕浏览追踪(Screen)
import { useFocusEffect } from '@react-navigation/native';
const ProductScreen = ({ route }) => {
useFocusEffect(
React.useCallback(() => {
// 当屏幕获得焦点时触发
DittofeedSdk.screen({
userId: 'current_user_id', // 从状态管理获取
name: 'Product Detail',
properties: {
productId: route.params?.productId,
category: route.params?.category,
viewTimestamp: new Date().toISOString(),
},
});
}, [route.params])
);
return (
// 屏幕内容
);
};
高级配置选项
批量处理配置
const advancedConfig = {
writeKey: 'Basic your-write-key',
// 性能优化配置
flushAt: 20, // 每20个事件批量发送
flushInterval: 30000, // 30秒自动刷新
maxQueueSize: 1000, // 最大队列大小
// 网络配置
host: 'https://api.dittofeed.com',
path: '/v1/batch',
// 调试模式
debug: __DEV__, // 开发环境下启用调试
};
错误处理
const withErrorHandling = async (sdkMethod, ...args) => {
try {
const result = await sdkMethod(...args);
return result;
} catch (error) {
console.error('Dittofeed SDK Error:', error);
// 这里可以添加重试逻辑或错误上报
if (error.networkError) {
// 网络错误处理
retryLater(sdkMethod, ...args);
}
throw error;
}
};
// 使用示例
const safeIdentify = (userData) => {
return withErrorHandling(DittofeedSdk.identify, userData);
};
实际应用场景
电商应用集成
class EcommerceTracker {
static trackProductView(product) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Product Viewed',
properties: {
productId: product.id,
name: product.name,
price: product.price,
category: product.category,
},
});
}
static trackAddToCart(product, quantity = 1) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Product Added to Cart',
properties: {
productId: product.id,
name: product.name,
quantity: quantity,
price: product.price,
total: product.price * quantity,
},
});
}
static trackPurchase(order) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Order Completed',
properties: {
orderId: order.id,
total: order.total,
items: order.items.length,
paymentMethod: order.paymentMethod,
},
});
}
static getUserId() {
// 从状态管理或AsyncStorage获取用户ID
return 'user_123';
}
}
社交媒体应用集成
class SocialMediaTracker {
static trackPostCreation(post) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Post Created',
properties: {
postId: post.id,
contentType: post.type,
length: post.content.length,
hasMedia: !!post.media,
},
});
}
static trackLike(postId) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Post Liked',
properties: {
postId: postId,
timestamp: new Date().toISOString(),
},
});
}
static trackComment(postId, commentLength) {
DittofeedSdk.track({
userId: this.getUserId(),
event: 'Comment Posted',
properties: {
postId: postId,
commentLength: commentLength,
},
});
}
}
性能优化最佳实践
批量处理策略
// 自定义批量处理器
class OptimizedTracker {
constructor() {
this.pendingEvents = [];
this.flushThreshold = 10;
this.flushTimeout = null;
}
queueEvent(eventData) {
this.pendingEvents.push(eventData);
if (this.pendingEvents.length >= this.flushThreshold) {
this.flushEvents();
} else if (!this.flushTimeout) {
this.flushTimeout = setTimeout(() => this.flushEvents(), 5000);
}
}
async flushEvents() {
if (this.pendingEvents.length === 0) return;
const eventsToSend = [...this.pendingEvents];
this.pendingEvents = [];
try {
// 使用批量API发送事件
await DittofeedSdk.flush();
console.log(`Successfully sent ${eventsToSend.length} events`);
} catch (error) {
// 发送失败,重新加入队列
this.pendingEvents.unshift(...eventsToSend);
console.error('Failed to send events:', error);
}
if (this.flushTimeout) {
clearTimeout(this.flushTimeout);
this.flushTimeout = null;
}
}
}
网络状态感知
import NetInfo from '@react-native-community/netinfo';
class NetworkAwareTracker {
constructor() {
this.isOnline = true;
this.setupNetworkListener();
}
setupNetworkListener() {
NetInfo.addEventListener(state => {
this.isOnline = state.isConnected;
if (this.isOnline) {
// 网络恢复时立即刷新事件
DittofeedSdk.flush();
}
});
}
trackEvent(eventData) {
if (this.isOnline) {
// 在线时直接发送
DittofeedSdk.track(eventData);
} else {
// 离线时缓存到本地存储
this.cacheEvent(eventData);
}
}
async cacheEvent(eventData) {
// 实现本地存储逻辑
const cachedEvents = await AsyncStorage.getItem('cached_events') || '[]';
const events = JSON.parse(cachedEvents);
events.push({
...eventData,
cachedAt: new Date().toISOString()
});
await AsyncStorage.setItem('cached_events', JSON.stringify(events));
}
}
调试与故障排除
开发环境调试
// 启用详细日志
DittofeedSdk.init({
writeKey: 'Basic your-write-key',
debug: true, // 启用调试模式
logger: {
log: (message) => console.log('[Dittofeed]', message),
error: (message) => console.error('[Dittofeed]', message),
warn: (message) => console.warn('[Dittofeed]', message),
},
});
// 手动检查事件队列
const checkEventQueue = async () => {
const queueSize = await DittofeedSdk.getQueueSize();
console.log(`Current event queue size: ${queueSize}`);
};
// 强制立即发送所有事件
const forceFlush = async () => {
try {
await DittofeedSdk.flush();
console.log('Events flushed successfully');
} catch (error) {
console.error('Flush failed:', error);
}
};
常见问题解决
安全考虑
数据保护
// 敏感信息过滤
const sanitizeUserData = (userData) => {
const sensitiveFields = ['password', 'creditCard', 'ssn', 'token'];
const sanitized = { ...userData };
sensitiveFields.forEach(field => {
if (sanitized[field]) {
sanitized[field] = '[REDACTED]';
}
});
return sanitized;
};
// 安全的用户识别
const safeIdentify = (userId, traits) => {
const sanitizedTraits = sanitizeUserData(traits);
DittofeedSdk.identify({
userId: userId,
traits: sanitizedTraits,
});
};
合规性配置
// GDPR合规设置
const configurePrivacy = (userConsent) => {
if (!userConsent) {
// 用户未同意时禁用数据收集
DittofeedSdk.disable();
} else {
DittofeedSdk.enable();
}
};
// 数据保留策略
const configureDataRetention = () => {
DittofeedSdk.init({
writeKey: 'Basic your-write-key',
// 数据保留设置
dataResidency: 'eu', // 欧盟数据驻留
retentionPeriod: 30, // 30天数据保留
});
};
总结
Dittofeed的React Native SDK为移动应用提供了强大的用户行为追踪和消息推送能力。通过本文的详细指南,您可以:
- 快速集成:通过简单的安装和配置步骤
- 全面追踪:实现用户识别、事件追踪和屏幕浏览
- 性能优化:利用批量处理和网络感知机制
- 安全合规:确保数据保护和隐私合规
通过合理的集成和配置,Dittofeed能够帮助您更好地理解用户行为,实现精准的消息推送和用户互动,最终提升应用的用户体验和业务价值。
更多推荐



所有评论(0)