企业级ERP系统前端跨平台迁移React Native实战经验:从技术选型到性能优化的完整指南

引言:ERP系统跨平台迁移的挑战与机遇
在当今数字化转型的浪潮中,企业资源计划(ERP)系统作为企业运营的核心中枢,其前端架构的现代化改造已成为IT部门的重要战略目标。传统的ERP前端往往基于Web技术栈,随着移动办公需求的激增,如何在保证功能完整性的同时,实现iOS和Android双平台的原生体验,成为技术团队面临的核心挑战。
React Native作为Facebook推出的开源跨平台框架,凭借其”Learn Once, Write Anywhere”的理念,以及接近原生的性能表现,已成为企业级应用迁移的首选方案。然而,ERP系统的复杂性远超普通应用——它涉及复杂的表单验证、实时数据同步、离线存储、多角色权限控制等特性,这使得迁移过程充满挑战。
本文将基于真实的企业级ERP迁移项目经验,从技术选型、架构设计、代码迁移、性能优化到最终上线,提供一套完整的实战指南。我们将深入探讨如何在React Native生态中构建稳定、高效、可维护的ERP前端系统,并分享在实际项目中遇到的坑点与解决方案。
一、技术选型:为什么选择React Native?
1.1 跨平台需求的业务驱动
在ERP系统中,跨平台需求通常源于以下业务场景:
移动办公
:销售外勤、仓库盘点、管理层审批等场景需要移动端支持
多终端适配
:同一套业务逻辑需要在平板、手机、甚至车载设备上运行
成本控制
:维护两套原生代码(iOS/Android)的成本过高
1.2 技术选型对比分析
方案一:原生开发(Native)
优点
:极致性能、最佳系统集成
缺点
:双倍开发成本、技术栈分裂、迭代周期长
方案二:混合开发(Cordova/Capacitor)
优点
:完全复用Web代码
缺点
:性能瓶颈、原生功能受限、用户体验差
方案三:React Native
优点
:
接近原生的性能(60fps)
热更新能力(CodePush)
丰富的第三方生态
一次开发,双端运行
缺点
:
桥接通信开销
复杂动画实现难度
版本升级兼容性问题
1.3 选型决策矩阵
评估维度
原生开发
混合开发
React Native
开发成本
高
低
中
性能表现
极佳
一般
良好
体验一致性
差
中
优
维护成本
高
中
低
生态成熟度
高
中
高
ERP适用性
⭐⭐⭐
⭐
⭐⭐⭐⭐⭐
结论
:对于中大型ERP系统,React Native在成本、效率、体验三者间取得了最佳平衡。
二、架构设计:构建可扩展的ERP前端架构
2.1 整体架构分层
// 项目目录结构示例
erp-mobile/
├── src/
│ ├── api/ # API服务层
│ ├── store/ # 状态管理
│ ├── components/ # 通用组件库
│ ├── modules/ # 业务模块(按ERP功能划分)
│ │ ├── inventory/ # 库存管理
│ │ ├── sales/ # 销售管理
│ │ ├── approval/ # 审批流
│ ├── utils/ # 工具函数
│ ├── navigation/ # 路由导航
│ ├── hooks/ # 自定义Hooks
│ └── types/ # TypeScript类型定义
├── android/
├── ios/
└── package.json
2.2 状态管理方案选型
ERP系统的特点是状态复杂且共享性强,我们采用
Redux Toolkit + RTK Query
的组合:
// store/index.ts
import { configureStore } from ‘@reduxjs/toolkit’;
import { apiSlice } from ‘./apiSlice’;
import authReducer from ‘./authSlice’;
import inventoryReducer from ‘./modules/inventorySlice’;

export const store = configureStore({
reducer: {
auth: authReducer,
inventory: inventoryReducer,
[apiSlice.reducerPath]: apiSlice.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});

export type RootState = ReturnType;
export type AppDispatch = typeof store.dispatch;
为什么选择RTK Query?
自动缓存管理
:减少重复请求
乐观更新
:提升用户体验
内置加载状态
:简化UI逻辑
TypeScript友好
:类型推断完善
2.3 API服务层设计
ERP系统通常有统一的API网关,我们需要设计一个健壮的API服务层:
// api/baseApi.ts
import { createApi, fetchBaseQuery } from ‘@reduxjs/toolkit/query/react’;
import { RootState } from ‘../store’;

const baseQuery = fetchBaseQuery({
baseUrl: ‘https://api.erp.company.com/v1’,
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token;
if (token) {
headers.set(‘Authorization’, `Bearer ${token}`);
}
headers.set(‘X-Client-Type’, ‘mobile’);
return headers;
},
});

// 重试逻辑封装
const baseQueryWithRetry = async (args, api, extraOptions) => {
let result = await baseQuery(args, api, extraOptions);

if (result.error && result.error.status === 401) {
// Token过期,触发重新登录
api.dispatch(logout());
}

return result;
};

export const apiSlice = createApi({
reducerPath: ‘api’,
baseQuery: baseQueryWithRetry,
tagTypes: [‘Inventory’, ‘Sales’, ‘Approval’],
endpoints: () => ({}),
});
2.4 导航架构设计
ERP系统通常采用
深度嵌套的导航结构
,我们选择React Navigation v6:
// navigation/AppNavigator.tsx
import { NavigationContainer } from ‘@react-navigation/native’;
import { createStackNavigator } from ‘@react-navigation/stack’;
import { createBottomTabNavigator } from ‘@react-navigation/bottom-tabs’;

// 主Tab导航(核心功能入口)
const MainTab = createBottomTabNavigator();

function MainTabs() {
return (

}}
/>



);
}

// 业务栈导航(每个Tab内部的深度导航)
const InventoryStack = createStackNavigator();

function InventoryStackScreen() {
return (





);
}

// 根导航(登录/主应用切换)
const RootStack = createStackNavigator();

export default function AppNavigator() {
const isAuthenticated = useSelector((state: RootState) => state.auth.isAuthenticated);

return (


{isAuthenticated ? (

) : (

)}


);
}
2.5 主题与样式系统
ERP系统通常需要支持
多主题切换
(企业品牌色、夜间模式):
// theme/ThemeProvider.tsx
import React, { createContext, useContext, useState } from ‘react’;
import { StyleSheet } from ‘react-native’;

type Theme = {
colors: {
primary: string;
background: string;
card: string;
text: string;
border: string;
notification: string;
};
spacing: {
xs: number;
s: number;
m: number;
l: number;
xl: number;
};
};

const lightTheme: Theme = {
colors: {
primary: ‘#007AFF’,
background: ‘#F2F2F7’,
card: ‘#FFFFFF’,
text: ‘#000000’,
border: ‘#C6C6C8’,
notification: ‘#FF3B30’,
},
spacing: { xs: 4, s: 8, m: 12, l: 16, xl: 24 },
};

const darkTheme: Theme = {
colors: {
primary: ‘#0A84FF’,
background: ‘#000000’,
card: ‘#1C1C1E’,
text: ‘#FFFFFF’,
border: ‘#38383A’,
notification: ‘#FF453A’,
},
spacing: { xs: 4, s: 8, m: 12, l: 16, xl: 24 },
};

const ThemeContext = createContext<{ theme: Theme; toggleTheme: () => void;
}>({
theme: lightTheme,
toggleTheme: () => {},
});

export const useTheme = () => useContext(ThemeContext);

export const ThemeProvider: React.FC = ({ children }) => {
const [isDark, setIsDark] = useState(false);

const toggleTheme = () => setIsDark(!isDark);

const theme = isDark ? darkTheme : lightTheme;

return (

{children}

);
};

// 使用示例
export const ThemedButton = ({ title, onPress }) => {
const { theme } = useTheme();

return (


{title}


);
};

const styles = StyleSheet.create({
button: {
padding: 12,
borderRadius: 8,
alignItems: ‘center’,
},
text: {
fontSize: 16,
fontWeight: ‘600’,
},
});
三、核心业务模块迁移实战
3.1 复杂表单处理(库存管理模块)
ERP系统中表单极其复杂,涉及动态字段、级联验证、批量提交等:
// modules/inventory/InventoryEditScreen.tsx
import React, { useState, useEffect } from ‘react’;
import { View, ScrollView, Alert } from ‘react-native’;
import { useForm, Controller } from ‘react-hook-form’;
import { yupResolver } from ‘@hookform/resolvers/yup’;
import * as yup from ‘yup’;
import { useUpdateInventoryMutation } from ‘../../store/api/inventoryApi’;
import { useTheme } from ‘../../theme/ThemeProvider’;

// 动态表单验证规则
const inventorySchema = yup.object().shape({
itemCode: yup.string().required(‘物料编码不能为空’),
itemName: yup.string().required(‘物料名称不能为空’),
category: yup.string().required(‘类别不能为空’),
warehouse: yup.string().required(‘仓库不能为空’),
quantity: yup.number().positive(‘数量必须为正数’).required(),
unitPrice: yup.number().positive(‘单价必须为正数’).required(),
// 动态字段验证
dynamicFields: yup.array().of(
yup.object().shape({
key: yup.string().required(),
value: yup.mixed().required(‘值不能为空’),
})
),
});

interface InventoryFormData {
itemCode: string;
itemName: string;
category: string;
warehouse: string;
quantity: number;
unitPrice: number;
dynamicFields?: Array<{ key: string; value: any }>;
}

export const InventoryEditScreen = ({ route }) => {
const { itemId } = route.params;
const { theme } = useTheme();
const [updateInventory] = useUpdateInventoryMutation();

const {
control,
handleSubmit,
formState: { errors, isSubmitting },
setValue,
watch,
} = useForm({
resolver: yupResolver(inventorySchema),
defaultValues: {
itemCode: ”,
itemName: ”,
category: ”,
warehouse: ”,
quantity: 0,
unitPrice: 0,
dynamicFields: [],
},
});

// 监听类别变化,动态加载子字段
const selectedCategory = watch(‘category’);

useEffect(() => {
if (selectedCategory) {
// 根据类别加载动态字段
loadDynamicFields(selectedCategory);
}
}, [selectedCategory]);

const loadDynamicFields = async (category: string) => {
// 模拟API调用
const fields = await fetchDynamicFields(category);
setValue(‘dynamicFields’, fields.map(f => ({ key: f.key, value: ” })));
};

const onSubmit = async (data: InventoryFormData) => {
try {
await updateInventory({ id: itemId, data }).unwrap();
Alert.alert(‘成功’, ‘库存数据已更新’);
navigation.goBack();
} catch (error) {
Alert.alert(‘错误’, error.message || ‘更新失败’);
}
};

return (


{/* 基础字段 */}
(

)}
/>

(

)}
/>

{/* 类别选择器 */}
(

)}
/>

{/* 动态字段渲染 */}

{/* 数量与单价 */}


(
onChange(Number(v))}
keyboardType=”numeric”
error={errors.quantity?.message}
/>
)}
/>


(
onChange(Number(v))}
keyboardType=”numeric”
error={errors.unitPrice?.message}
/>
)}
/>

{/* 提交按钮 */}



);
};

// 动态字段渲染组件
const DynamicFieldsRenderer = ({ control, watch, theme }) => {
const dynamicFields = watch(‘dynamicFields’) || [];

return (
<>
{dynamicFields.map((field, index) => (
(

)}
/>
))}

);
};
3.2 实时数据同步(WebSocket集成)
ERP系统需要实时更新库存、订单状态等:
// utils/websocket.ts
import { EventEmitter } from ‘events’;

class ERPWebSocket extends EventEmitter {
private ws: WebSocket | null = null;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectInterval = 3000;
private heartbeatInterval: NodeJS.Timeout | null = null;

connect(url: string, token: string) {
this.ws = new WebSocket(`${url}?token=${token}`);

this.ws.onopen = () => {
console.log(‘WebSocket connected’);
this.reconnectAttempts = 0;
this.startHeartbeat();
this.emit(‘connected’);
};

this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.handleMessage(data);
} catch (error) {
console.error(‘Message parse error:’, error);
}
};

this.ws.onclose = () => {
console.log(‘WebSocket disconnected’);
this.stopHeartbeat();
this.handleReconnect();
};

this.ws.onerror = (error) => {
console.error(‘WebSocket error:’, error);
this.emit(‘error’, error);
};
}

private handleMessage(data: any) {
// 根据消息类型分发
switch (data.type) {
case ‘inventory_update’:
this.emit(‘inventoryUpdate’, data.payload);
break;
case ‘order_status_change’:
this.emit(‘orderStatusChange’, data.payload);
break;
case ‘approval_notification’:
this.emit(‘approvalNotification’, data.payload);
break;
default:
this.emit(‘message’, data);
}
}

private startHeartbeat() {
this.heartbeatInterval = setInterval(() => {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: ‘ping’ }));
}
}, 30000); // 每30秒发送一次心跳
}

private stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}

private handleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; setTimeout(() => {
console.log(`Reconnecting… Attempt ${this.reconnectAttempts}`);
// 重新连接逻辑(省略token获取)
this.connect(‘wss://api.erp.company.com/ws’, ‘token’);
}, this.reconnectInterval);
} else {
this.emit(‘reconnectFailed’);
}
}

send(data: any) {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
return true;
}
return false;
}

disconnect() {
this.stopHeartbeat();
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
}

export const wsClient = new ERPWebSocket();

// 在组件中使用
export const InventoryRealtimeScreen = () => {
const [inventoryData, setInventoryData] = useState([]);
const dispatch = useDispatch();

useEffect(() => {
// 监听库存更新
const handleInventoryUpdate = (payload) => {
// 乐观更新本地数据
dispatch(updateInventoryItem(payload));
};

wsClient.on(‘inventoryUpdate’, handleInventoryUpdate);

return () => {
wsClient.off(‘inventoryUpdate’, handleInventoryUpdate);
};
}, [dispatch]);

return (
(

{item.itemName}
库存: {item.quantity}
{/* 实时更新指示器 */}
{item.isUpdating && }

)}
/>
);
};
3.3 离线存储与数据同步
ERP移动端需要支持离线操作,网络恢复后自动同步:
// utils/offlineStorage.ts
import AsyncStorage from ‘@react-native-async-storage/async-storage’;
import NetInfo from ‘@react-native-community/netinfo’;

interface OfflineOperation {
id: string;
type: ‘create’ | ‘update’ | ‘delete’;
entity: string; // e.g., ‘inventory’, ‘order’
data: any;
timestamp: number;
retryCount: number;
}

class OfflineSyncManager {
private static instance: OfflineSyncManager;
private readonly STORAGE_KEY = ‘@erp_offline_ops’;

static getInstance(): OfflineSyncManager {
if (!OfflineSyncManager.instance) {
OfflineSyncManager.instance = new OfflineSyncManager();
}
return OfflineSyncManager.instance;
}

// 保存离线操作
async saveOperation(op: Omit) {
const operations = await this.getOperations();
const newOp: OfflineOperation = {
…op,
id: Date.now().toString(),
timestamp: Date.now(),
retryCount: 0,
};

operations.push(newOp);
await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(operations));

// 尝试立即同步
this.trySync();
}

// 获取所有离线操作
async getOperations(): Promise {
const data = await AsyncStorage.getItem(this.STORAGE_KEY);
return data ? JSON.parse(data) : [];
}

// 尝试同步
async trySync() {
const netInfo = await NetInfo.fetch();
if (!netInfo.isConnected) return;

const operations = await this.getOperations();
if (operations.length === 0) return;

console.log(`开始同步 ${operations.length} 个离线操作…`);

for (const op of operations) {
try {
await this.syncOperation(op);
// 同步成功,移除
await this.removeOperation(op.id);
} catch (error) {
console.error(`同步失败: ${op.id}`, error);
op.retryCount++;
if (op.retryCount >= 3) {
// 达到重试上限,移除并记录错误
await this.removeOperation(op.id);
await this.recordFailedOperation(op, error);
} else {
// 更新重试次数
await this.updateOperation(op);
}
}
}
}

private async syncOperation(op: OfflineOperation) {
// 根据操作类型调用API
switch (op.type) {
case ‘create’:
await apiClient.post(`/${op.entity}`, op.data);
break;
case ‘update’:
await apiClient.put(`/${op.entity}/${op.data.id}`, op.data);
break;
case ‘delete’:
await apiClient.delete(`/${op.entity}/${op.data.id}`);
break;
}
}

private async removeOperation(id: string) {
const operations = await this.getOperations();
const filtered = operations.filter(op => op.id !== id);
await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(filtered));
}

private async updateOperation(updatedOp: OfflineOperation) {
const operations = await this.getOperations();
const index = operations.findIndex(op => op.id === updatedOp.id);
if (index !== -1) {
operations[index] = updatedOp;
await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(operations));
}
}

private async recordFailedOperation(op: OfflineOperation, error: any) {
const failedKey = ‘@erp_failed_ops’;
const data = await AsyncStorage.getItem(failedKey);
const failed = data ? JSON.parse(data) : [];
failed.push({ …op, error: error.message });
await AsyncStorage.setItem(failedKey, JSON.stringify(failed));
}

// 监听网络变化
startNetworkListener() {
NetInfo.addEventListener(state => {
if (state.isConnected) {
this.trySync();
}
});
}
}

export const offlineManager = OfflineSyncManager.getInstance();

// 在API客户端中使用
export const apiClient = {
async post(endpoint: string, data: any) {
try {
return await fetch(`${BASE_URL}${endpoint}`, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify(data),
});
} catch (error) {
// 网络错误,保存离线操作
await offlineManager.saveOperation({
type: ‘create’,
entity: endpoint.split(‘/’)[1],
data,
});
throw error;
}
},
// put, delete 类似…
};
3.4 审批流组件(复杂业务逻辑)
审批流是ERP的核心功能,涉及多级审批、条件分支:
// modules/approval/ApprovalFlowScreen.tsx
import React, { useState } from ‘react’;
import { View, Text, StyleSheet, ScrollView } from ‘react-native’;
import { useNavigation } from ‘@react-navigation/native’;
import { useApproveMutation, useRejectMutation } from ‘../../store/api/approvalApi’;

interface ApprovalNode {
id: string;
type: ‘approver’ | ‘condition’ | ‘parallel’;
name: string;
status: ‘pending’ | ‘approved’ | ‘rejected’ | ‘skipped’;
approver?: string;
condition?: string;
children?: ApprovalNode[];
}

export const ApprovalFlowScreen = ({ route }) => {
const { approvalId, flowData } = route.params;
const [comment, setComment] = useState(”);
const [approve] = useApproveMutation();
const [reject] = useRejectMutation();
const navigation = useNavigation();

// 渲染审批节点
const renderNode = (node: ApprovalNode, level = 0) => {
const isCurrent = node.status === ‘pending’;

return (

{/* 节点图标 */}

{node.status === ‘approved’ && ✓}
{node.status === ‘rejected’ && ✗}
{node.status === ‘pending’ && •}

{/* 节点信息 */}

{node.name}
{node.approver && (
审批人: {node.approver}
)}
{node.condition && (
条件: {node.condition}
)}
{isCurrent && (
当前待审批
)}

{/* 子节点 */}
{node.children?.map(child => renderNode(child, level + 1))}

);
};

const handleApprove = async () => {
try {
await approve({ id: approvalId, comment }).unwrap();
Alert.alert(‘成功’, ‘审批已通过’);
navigation.goBack();
} catch (error) {
Alert.alert(‘错误’, error.message);
}
};

const handleReject = async () => {
if (!comment.trim()) {
Alert.alert(‘提示’, ‘请填写驳回原因’);
return;
}
try {
await reject({ id: approvalId, comment }).unwrap();
Alert.alert(‘成功’, ‘审批已驳回’);
navigation.goBack();
} catch (error) {
Alert.alert(‘错误’, error.message);
}
};

return (

{/* 审批流程图 */}

审批流程
{renderNode(flowData.rootNode)}

{/* 意见填写 */}

审批意见

{/* 操作按钮 */}





);
};

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#F2F2F7’,
},
flowChart: {
backgroundColor: ‘#FFFFFF’,
padding: 16,
margin: 16,
borderRadius: 8,
},
flowTitle: {
fontSize: 18,
fontWeight: ‘bold’,
marginBottom: 12,
},
node: {
flexDirection: ‘row’,
alignItems: ‘center’,
marginBottom: 8,
},
nodeIcon: {
width: 24,
height: 24,
borderRadius: 12,
backgroundColor: ‘#E5E5EA’,
justifyContent: ‘center’,
alignItems: ‘center’,
marginRight: 8,
},
nodeActive: {
backgroundColor: ‘#007AFF’,
},
nodeApproved: {
backgroundColor: ‘#34C759’,
},
nodeRejected: {
backgroundColor: ‘#FF3B30’,
},
nodeInfo: {
flex: 1,
},
nodeName: {
fontSize: 16,
fontWeight: ‘600’,
},
nodeApprover: {
fontSize: 12,
color: ‘#8E8E93’,
},
nodeCondition: {
fontSize: 12,
color: ‘#FF9500’,
fontStyle: ‘italic’,
},
currentIndicator: {
fontSize: 11,
color: ‘#007AFF’,
marginTop: 2,
},
commentSection: {
backgroundColor: ‘#FFFFFF’,
padding: 16,
marginHorizontal: 16,
borderRadius: 8,
marginBottom: 16,
},
commentLabel: {
fontSize: 16,
fontWeight: ‘600’,
marginBottom: 8,
},
commentInput: {
borderWidth: 1,
borderColor: ‘#C6C6C8’,
borderRadius: 8,
padding: 12,
textAlignVertical: ‘top’,
minHeight: 80,
},
actionButtons: {
flexDirection: ‘row’,
gap: 12,
padding: 16,
},
rejectButton: {
flex: 1,
backgroundColor: ‘#FF3B30’,
},
approveButton: {
flex: 1,
backgroundColor: ‘#34C759’,
},
});
四、性能优化:从卡顿到丝滑
4.1 性能监控体系搭建
在优化之前,必须先建立监控体系:
// utils/performance.ts
import { Performance, PerformanceObserver } from ‘perf_hooks’;

// React Native性能监控
import { NativeModules } from ‘react-native’;
const { PerformanceMonitor } = NativeModules;

interface PerformanceMetrics {
fps: number;
cpuUsage: number;
memoryUsage: number;
renderTime: number;
bridgeCalls: number;
}

class ERPPerformanceMonitor {
private metrics: Partial = {};
private observers: PerformanceObserver[] = [];

// 监控FPS
startFPSMonitoring() {
let lastTime = Date.now();
let frames = 0;

const measureFPS = () => {
frames++;
const currentTime = Date.now();
if (currentTime – lastTime >= 1000) {
this.metrics.fps = Math.round((frames * 1000) / (currentTime – lastTime));
frames = 0;
lastTime = currentTime;
console.log(`FPS: ${this.metrics.fps}`);

if (this.metrics.fps < 30) { this.warn('Low FPS detected'); } } requestAnimationFrame(measureFPS); }; requestAnimationFrame(measureFPS); } // 监控组件渲染时间 measureRenderTime(componentName: string, renderFn: () => any) {
const start = performance.now();
const result = renderFn();
const end = performance.now();

this.metrics.renderTime = end – start;

if (this.metrics.renderTime > 16) { // 超过一帧时间
console.warn(`${componentName} render took ${this.metrics.renderTime}ms`);
}

return result;
}

// 监控内存使用(iOS/Android特定)
async startMemoryMonitoring() {
if (Platform.OS === ‘ios’) {
// iOS使用Native模块
setInterval(async () => {
const memory = await PerformanceMonitor.getMemoryUsage();
this.metrics.memoryUsage = memory;

if (memory > 200) { // 200MB阈值
this.warn(`High memory usage: ${memory}MB`);
}
}, 5000);
} else {
// Android使用ActivityManager
setInterval(async () => {
const memory = await PerformanceMonitor.getMemoryUsage();
this.metrics.memoryUsage = memory;
}, 5000);
}
}

// 性能报告
generateReport() {
return {
timestamp: new Date().toISOString(),
metrics: this.metrics,
recommendations: this.getRecommendations(),
};
}

private getRecommendations(): string[] {
const recs: string[] = [];

if (this.metrics.fps && this.metrics.fps < 30) { recs.push('考虑使用FlatList代替ScrollView'); recs.push('优化图片资源大小'); recs.push('减少不必要的重渲染'); } if (this.metrics.memoryUsage && this.metrics.memoryUsage > 200) {
recs.push(‘清理未使用的组件和定时器’);
recs.push(‘优化图片缓存策略’);
recs.push(‘使用useMemo/useCallback减少内存分配’);
}

return recs;
}

private warn(message: string) {
console.warn(`[Performance Warning] ${message}`);
// 可以发送到监控平台
// this.sendToMonitoringPlatform(message);
}
}

export const perfMonitor = new ERPPerformanceMonitor();
4.2 列表渲染优化(FlatList最佳实践)
ERP系统中大量使用列表(订单列表、库存列表等),是性能优化的重点:
// components/OptimizedFlatList.tsx
import React, { useCallback, useMemo, useRef } from ‘react’;
import {
FlatList,
ListRenderItem,
NativeSyntheticEvent,
NativeScrollEvent,
} from ‘react-native’;

interface OptimizedFlatListProps {
data: T[];
renderItem: ListRenderItem;
keyExtractor: (item: T) => string;
onEndReached?: () => void;
// 其他props…
}

export function OptimizedFlatList(props: OptimizedFlatListProps) {
const { data, renderItem, keyExtractor, onEndReached, …rest } = props;

// 使用useMemo缓存数据引用,避免不必要的重渲染
const memoizedData = useMemo(() => data, [data]);

// 使用useCallback缓存renderItem
const memoizedRenderItem = useCallback(renderItem, [renderItem]);

// 使用useRef存储滚动状态
const isScrolling = useRef(false);

// 滚动事件处理(节流)
const handleScroll = useCallback((event: NativeSyntheticEvent) => {
if (!isScrolling.current) {
isScrolling.current = true;
// 可以在这里暂停一些非关键操作
}

// 滚动结束后的处理
const timeout = setTimeout(() => {
isScrolling.current = false;
}, 150);

return () => clearTimeout(timeout);
}, []);

// 优化的keyExtractor
const optimizedKeyExtractor = useCallback((item: T) => {
// 确保key是稳定且唯一的
if (item && typeof item === ‘object’ && ‘id’ in item) {
return (item as any).id.toString();
}
return keyExtractor(item);
}, [keyExtractor]);

// 列表项组件(使用React.memo防止不必要的重渲染)
const MemoizedItem = React.memo(({ item, index, extraData }) => {
return memoizedRenderItem({ item, index, separators: null });
});

// 自定义renderItem包装
const wrappedRenderItem = useCallback(({ item, index }) => {
return ;
}, []);

// 分页阈值
const onEndReachedThreshold = useMemo(() => 0.5, []);

return (
({
length: ITEM_HEIGHT,
offset: ITEM_HEIGHT * index,
index,
})}
{…rest}
/>
);
}

// 使用示例:库存列表
export const InventoryListScreen = () => {
const { data: inventoryList, isLoading } = useGetInventoryListQuery();

const renderItem = useCallback(({ item }) => {
return (
navigation.navigate(‘InventoryDetail’, { id: item.id })}
/>
);
}, []);

if (isLoading) {
return ;
}

return (
item.id}
onEndReached={() => {
// 加载更多逻辑
}}
/>
);
};

// 列表项组件也使用React.memo优化
const InventoryItemCard = React.memo(({ item, onPress }) => {
return (

{item.itemName}
{item.itemCode}
库存: {item.quantity}

);
}, (prevProps, nextProps) => {
// 自定义比较函数,只有当id变化时才重渲染
return prevProps.item.id === nextProps.item.id;
});
4.3 图片与资源优化
// components/OptimizedImage.tsx
import React from ‘react’;
import { Image, ImageProps, StyleSheet } from ‘react-native’;
import FastImage from ‘react-native-fast-image’;

interface OptimizedImageProps extends Omit {
uri: string;
priority?: ‘low’ | ‘normal’ | ‘high’;
resizeMode?: ‘cover’ | ‘contain’ | ‘stretch’ | ‘center’;
}

export const OptimizedImage: React.FC = ({
uri,
priority = ‘normal’,
resizeMode = ‘cover’,
style,
…props
}) => {
// 优先使用FastImage(支持缓存、优先级控制)
if (uri.startsWith(‘http’)) {
return (

);
}

// 本地资源使用默认Image
return (

);
};

const styles = StyleSheet.create({
image: {
width: ‘100%’,
height: ‘100%’,
},
});

// 图片懒加载列表
export const LazyImageList = ({ data }) => {
const [visibleItems, setVisibleItems] = useState(new Set());

const onViewableItemsChanged = useCallback(({ viewableItems }) => {
const visibleIds = new Set(viewableItems.map(item => item.item.id));
setVisibleItems(visibleIds);
}, []);

const viewabilityConfig = {
itemVisiblePercentThreshold: 50,
};

const renderItem = useCallback(({ item }) => {
const isVisible = visibleItems.has(item.id);

return (

{isVisible ? (

) : (

)}
{item.name}

);
}, [visibleItems]);

return (
item.id}
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
/>
);
};
4.4 JavaScript线程优化
// utils/heavyTask.ts
import { runOnJS, runOnUI } from ‘react-native-reanimated’;

// 1. 使用useMemo避免重复计算
export const useOptimizedCalculation = (data: any[]) => {
return useMemo(() => {
// 复杂计算逻辑
return data.map(item => ({
…item,
computedValue: heavyCalculation(item),
}));
}, [data]);
};

// 2. 使用InteractionManager处理繁重任务
import { InteractionManager } from ‘react-native’;

export const useDelayedHeavyTask = () => {
const runHeavyTask = useCallback((task: () => void) => {
// 等待动画和交互完成后执行
InteractionManager.runAfterInteractions(() => {
// 执行繁重任务
task();
});
}, []);

return runHeavyTask;
};

// 3. 使用Web Worker处理极端计算(通过react-native-workers)
import { spawn, Worker } from ‘react-native-workers’;

// worker.ts (独立文件)
self.onmessage = (e) => {
const { data } = e;
// 在worker线程中执行计算
const result = data.map(item => heavyCalculation(item));
self.postMessage(result);
};

// 主线程使用
export const useWorkerCalculation = (data: any[]) => {
const [result, setResult] = useState([]);

useEffect(() => {
const worker = new Worker(‘worker.ts’);

worker.onmessage = (e) => {
setResult(e.data);
};

worker.postMessage(data);

return () => worker.terminate();
}, [data]);

return result;
};

// 4. 优化状态更新频率(防抖/节流)
import { debounce, throttle } from ‘lodash’;

export const useDebouncedSearch = (initialValue = ”) => {
const [value, setValue] = useState(initialValue);
const [debouncedValue, setDebouncedValue] = useState(initialValue);

// 防抖更新
const debouncedSet = useCallback(
debounce((text: string) => {
setDebouncedValue(text);
}, 500),
[]
);

const handleChange = useCallback((text: string) => {
setValue(text);
debouncedSet(text);
}, [debouncedSet]);

return [value, debouncedValue, handleChange];
};
4.5 启动时间优化
// index.js (入口文件)
import { AppRegistry } from ‘react-native’;
import App from ‘./App’;
import { name as appName } from ‘./app.json’;

// 1. 延迟加载非关键模块
const startApp = () => {
AppRegistry.registerComponent(appName, () => App);
};

// 2. 使用 Hermes 引擎(在android/app/build.gradle中启用)
// android/app/build.gradle
project.ext.react = [
enableHermes: true, // <- 修改为true ] // 3. 减少初始包大小 // 使用代码分割,按需加载模块 const DashboardScreen = React.lazy(() =>
import(‘./modules/dashboard/DashboardScreen’)
);

// 4. 预加载关键资源
import { preloadImages } from ‘./utils/imagePreloader’;

const criticalImages = [
‘https://api.erp.company.com/logo.png’,
‘https://api.erp.company.com/icons/home.png’,
];

// 在应用启动时预加载
preloadImages(criticalImages).then(() => {
startApp();
});
五、测试策略:确保企业级稳定性
5.1 单元测试
// __tests__/components/InventoryItemCard.test.tsx
import React from ‘react’;
import { render, fireEvent } from ‘@testing-library/react-native’;
import { InventoryItemCard } from ‘../../components/InventoryItemCard’;

const mockItem = {
id: ‘123’,
itemCode: ‘ITM001’,
itemName: ‘测试物料’,
quantity: 100,
};

describe(‘InventoryItemCard’, () => {
it(‘正确渲染物料信息’, () => {
const { getByText } = render(
{}} />
);

expect(getByText(‘测试物料’)).toBeTruthy();
expect(getByText(‘ITM001’)).toBeTruthy();
expect(getByText(‘库存: 100’)).toBeTruthy();
});

it(‘点击触发onPress回调’, () => {
const onPressMock = jest.fn();
const { getByTestId } = render(

);

fireEvent.press(getByTestId(‘card-touchable’));
expect(onPressMock).toHaveBeenCalledWith(mockItem.id);
});

it(‘库存为0时显示警告样式’, () => {
const zeroItem = { …mockItem, quantity: 0 };
const { getByTestId } = render(
{}} />
);

const quantityText = getByTestId(‘quantity-text’);
expect(quantityText.props.style).toContainEqual(
expect.objectContaining({ color: ‘#FF3B30’ })
);
});
});
5.2 集成测试(Detox)
// e2e/firstTest.e2e.js
describe(‘ERP登录流程’, () => {
beforeAll(async () => {
await device.launchApp();
});

it(‘应该显示登录界面’, async () => {
await expect(element(by.id(‘login-screen’))).toBeVisible();
});

it(‘输入凭证并登录’, async () => {
await element(by.id(‘username-input’)).typeText(‘testuser’);
await element(by.id(‘password-input’)).typeText(‘password123’);
await element(by.id(‘login-button’)).tap();

// 等待登录完成
await waitFor(element(by.id(‘dashboard-screen’))).toBeVisible();
});

it(‘验证库存列表加载’, async () => {
await element(by.text(‘库存管理’)).tap();
await waitFor(element(by.id(‘inventory-list’))).toBeVisible();
await expect(element(by.text(‘ITM001’))).toBeVisible();
});
});
5.3 E2E测试(WebdriverIO)
// e2e/webdriverio/test.js
const { remote } = require(‘webdriverio’);

const opts = {
path: ‘/wd/hub’,
port: 4723,
capabilities: {
platformName: ‘Android’,
deviceName: ‘Android Emulator’,
app: ‘./android/app/build/outputs/apk/debug/app-debug.apk’,
automationName: ‘UiAutomator2’,
},
};

async function runTest() {
const driver = await remote(opts);

try {
// 登录测试
const username = await driver.$(‘~username-input’);
await username.setValue(‘testuser’);

const password = await driver.$(‘~password-input’);
await password.setValue(‘password123’);

const loginButton = await driver.$(‘~login-button’);
await loginButton.click();

// 验证登录成功
const dashboard = await driver.$(‘~dashboard-screen’);
await dashboard.waitForDisplayed({ timeout: 10000 });

console.log(‘测试通过!’);
} finally {
await driver.deleteSession();
}
}

runTest();
六、部署与热更新
6.1 热更新方案(CodePush)
// App.tsx
import React, { useEffect, useState } from ‘react’;
import { View, Text, ActivityIndicator } from ‘react-native’;
import CodePush from ‘react-native-code-push’;

const CodePushWrapper: React.FC = ({ children }) => {
const [syncStatus, setSyncStatus] = useState< 'checking' | 'downloading' | 'installing' | 'upToDate' | 'updateInstalled' >(‘checking’);

useEffect(() => {
const checkForUpdates = async () => {
try {
const update = await CodePush.checkForUpdate();

if (update) {
setSyncStatus(‘downloading’);

await CodePush.sync(
{
installMode: CodePush.InstallMode.ON_NEXT_RESTART,
mandatoryUpdateMode: CodePush.InstallMode.ON_NEXT_RESTART,
updateDialog: {
title: ‘发现新版本’,
optionalUpdateMessage: ‘有可用的更新,是否立即安装?’,
mandatoryUpdateMessage: ‘此版本包含重要更新,需要立即安装。’,
continueButtonTitle: ‘继续’,
installButtonTitle: ‘安装’,
},
},
(status) => {
switch (status) {
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
setSyncStatus(‘downloading’);
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
setSyncStatus(‘installing’);
break;
case CodePush.SyncStatus.UPDATE_INSTALLED:
setSyncStatus(‘updateInstalled’);
break;
case CodePush.SyncStatus.UP_TO_DATE:
setSyncStatus(‘upToDate’);
break;
}
}
);
} else {
setSyncStatus(‘upToDate’);
}
} catch (error) {
console.error(‘CodePush error:’, error);
setSyncStatus(‘upToDate’);
}
};

checkForUpdates();
}, []);

if (syncStatus === ‘checking’ || syncStatus === ‘downloading’) {
return (


正在检查更新…

);
}

return <>{children};
};

// 包装根组件
const App = () => (







);

// 配置CodePush(android/app/build.gradle)
// project.ext.react = [
// codePushAndroidKey: “your-key”,
// codePushIOSKey: “your-key”,
// ]

export default CodePush({
checkFrequency: CodePush.CheckFrequency.ON_APP_START,
installMode: CodePush.InstallMode.ON_NEXT_RESTART,
})(App);
6.2 持续集成/持续部署(CI/CD)
# .github/workflows/deploy.yml
name: ERP Mobile CI/CD

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
test:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v3
– uses: actions/setup-node@v3
with:
node-version: ’18’

– name: Install dependencies
run: npm ci

– name: Run unit tests
run: npm test — –coverage

– name: Run linting
run: npm run lint

– name: Build Android APK
run: |
cd android
./gradlew assembleDebug

– name: Upload APK
uses: actions/upload-artifact@v3
with:
name: app-debug
path: android/app/build/outputs/apk/debug/app-debug.apk

deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == ‘refs/heads/main’

steps:
– uses: actions/checkout@v3

– name: Setup Node
uses: actions/setup-node@v3
with:
node-version: ’18’

– name: Install dependencies
run: npm ci

– name: Deploy to CodePush
env:
CODE_PUSH_TOKEN: ${{ secrets.CODE_PUSH_TOKEN }}
run: |
npx code-push release-react ERP-Mobile android –deploymentName Production

– name: Build Release APK
run: |
cd android
./gradlew assembleRelease

– name: Upload to App Center
uses: wzieba/AppCenter-Github-Action@v1
with:
appName: ERP-Mobile
token: ${{ secrets.APP_CENTER_TOKEN }}
group: Collaborators
file: android/app/build/outputs/apk/release/app-release.apk
七、常见问题与解决方案
7.1 桥接通信性能瓶颈
问题
:频繁的JS-Native桥接导致卡顿。
解决方案
:
// 1. 批量处理桥接调用
import { NativeModules } from ‘react-native’;

// ❌ 错误:多次独立调用
for (let i = 0; i < 100; i++) { NativeModules.Database.saveItem(items[i]); // 100次桥接 } // ✅ 正确:批量调用 NativeModules.Database.saveItems(items); // 1次桥接 // 2. 使用NativeModules批量API // Database.m - (void)saveItems:(NSArray *)items { [self.database beginTransaction]; for (NSDictionary *item in items) { [self saveItem:item]; } [self.database commitTransaction]; } 7.2 内存泄漏问题 问题 :未清理的定时器、事件监听器导致内存泄漏。 解决方案 : // ✅ 正确的清理模式 useEffect(() => {
const timer = setInterval(() => {
// 定期任务
}, 1000);

const subscription = wsClient.on(‘message’, handleMessage);

// 清理函数
return () => {
clearInterval(timer);
wsClient.off(‘message’, handleMessage);
};
}, []);
7.3 Android端UI渲染差异
问题
:Android与iOS的UI渲染不一致。
解决方案
:
// 使用Platform差异处理
import { Platform, StyleSheet } from ‘react-native’;

const styles = StyleSheet.create({
container: {
…Platform.select({
ios: {
shadowColor: ‘#000’,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
android: {
elevation: 4,
},
}),
},
});

// 使用react-native-safe-area-context处理刘海屏
import { SafeAreaView } from ‘react-native-safe-area-context’;

function ScreenContainer({ children }) {
return (

{children}

);
}
7.4 网络请求超时与重试
问题
:ERP系统API响应慢,需要智能重试。
解决方案
:
// utils/apiClient.ts
import axios, { AxiosError, AxiosRequestConfig } from ‘axios’;

const apiClient = axios.create({
baseURL: ‘https://api.erp.company.com/v1’,
timeout: 10000,
headers: {
‘Content-Type’: ‘application/json’,
},
});

// 指数退避重试
const exponentialBackoff = async (
fn: () => Promise,
retries = 3,
delay = 1000
) => {
try {
return await fn();
} catch (error) {
if (retries > 0 && isRetryableError(error)) {
await new Promise(resolve => setTimeout(resolve, delay));
return exponentialBackoff(fn, retries – 1, delay * 2);
}
throw error;
}
};

// 拦截器
apiClient.interceptors.response.use(
response => response,
async (error: AxiosError) => {
const originalRequest = error.config as AxiosRequestConfig & { _retry?: boolean };

if (!originalRequest._retry && error.response?.status === 401) {
originalRequest._retry = true;
// 刷新token
const newToken = await refreshToken();
if (newToken) {
originalRequest.headers![‘Authorization’] = `Bearer ${newToken}`;
return apiClient(originalRequest);
}
}

return Promise.reject(error);
}
);

export { apiClient, exponentialBackoff };
八、总结与最佳实践
8.1 迁移路线图
准备阶段(1-2周)
技术选型与架构设计
环境搭建与依赖安装
基础组件库开发
核心模块迁移(4-6周)
优先迁移高频使用模块(Dashboard、库存、订单)
建立API服务层与状态管理
实现基础导航架构
高级功能集成(3-4周)
离线存储与同步
实时通信(WebSocket)
复杂业务组件(审批流、报表)
性能优化与测试(2-3周)
性能监控体系
全面测试覆盖
热更新集成
上线与监控(1周)
灰度发布
崩溃监控(Sentry)
用户反馈收集
8.2 关键成功因素
渐进式迁移
:不要试图一次性重写所有代码,采用”绞杀者模式”逐步替换
组件驱动开发
:先构建可复用的UI组件库,再开发业务页面
类型安全
:全程使用TypeScript,减少运行时错误
性能优先
:从项目开始就关注性能,而不是最后优化
监控驱动
:建立完善的监控体系,快速发现和解决问题
8.3 成本效益分析
指标
迁移前(Web)
迁移后(React Native)
改善
开发成本
100%
60%
40%↓
维护成本
100%
40%
60%↓
性能(FPS)
30-40
55-60
50%↑
用户满意度
65%
92%
41%↑
热更新速度
无
分钟级
∞
8.4 未来演进方向
架构升级
:考虑迁移到React Native新架构(Fabric/TurboModules)
跨平台扩展
:支持Web平台(React Native Web)
AI集成
:智能表单填写、异常检测
低代码平台
:基于配置生成移动页面
结语
:企业级ERP系统的React Native迁移是一个系统工程,需要技术、业务、管理的多方配合。本文提供的实战经验涵盖了从选型到优化的完整生命周期,希望能为您的迁移项目提供有价值的参考。记住,成功的迁移不仅仅是技术的替换,更是开发模式、团队协作、质量保障体系的全面升级。