react native 如何实现热更新
React Native 热更新实现方法
React Native 热更新可以通过多种方式实现,以下是几种常见的方法:
使用 CodePush 服务
CodePush 是微软提供的一项服务,允许开发者直接推送更新到用户的应用程序,无需通过应用商店审核。
安装 CodePush CLI 和客户端库:
npm install -g code-push-cli
npm install react-native-code-push
链接原生模块(React Native 0.60+ 自动链接):
react-native link react-native-code-push
在 App.js 中包装根组件:
import codePush from "react-native-code-push";
let codePushOptions = { checkFrequency: codePush.CheckFrequency.ON_APP_START };
class MyApp extends Component {
// ...
}
export default codePush(codePushOptions)(MyApp);
创建部署并发布更新:

code-push release-react <appName> <platform>
使用 Expo 的 OTA 更新
如果使用 Expo 开发,可以利用其内置的 OTA(Over-The-Air)更新功能。
在 app.json 配置更新策略:
{
"expo": {
"updates": {
"enabled": true,
"checkAutomatically": "ON_LOAD",
"fallbackToCacheTimeout": 0
}
}
}
在代码中手动检查更新:

import * as Updates from 'expo-updates';
async function checkForUpdates() {
try {
const update = await Updates.checkForUpdateAsync();
if (update.isAvailable) {
await Updates.fetchUpdateAsync();
await Updates.reloadAsync();
}
} catch (e) {
// 处理错误
}
}
自定义实现热更新
对于需要更多控制的情况,可以自行实现热更新系统。
设置一个检查更新的 API 端点:
const checkForUpdate = async () => {
const response = await fetch('https://your-api.com/update-check');
const data = await response.json();
return data.updateAvailable ? data.bundleUrl : null;
};
下载并执行新 bundle:
const downloadAndApplyUpdate = async (bundleUrl) => {
const response = await fetch(bundleUrl);
const bundle = await response.text();
// 在 React Native 中执行新代码
const { scriptURL } = NativeModules.SourceCode;
const bundlePath = scriptURL.split('/').slice(0, -1).join('/') + '/updated.bundle';
// 写入文件系统
await RNFS.writeFile(bundlePath, bundle, 'utf8');
// 重新加载应用
if (Platform.OS === 'ios') {
NativeModules.DevSettings.reload('updated.bundle');
} else {
NativeModules.DevSettings.reload();
}
};
注意事项
- iOS 应用需要确保遵守 Apple 的审核指南,热更新不应更改应用的主要功能
- Android 应用需要注意文件系统权限问题
- 所有热更新方案都应包含回滚机制,以防更新失败
- 生产环境应使用签名验证确保 bundle 的安全性
- 考虑用户网络状况,大更新包可能需要分块下载或提示用户连接 WiFi
版本控制策略
实现有效的版本控制对热更新至关重要:
const versionCheck = async () => {
const currentVersion = require('./package.json').version;
const serverVersion = await fetchVersionFromServer();
if (compareVersions(serverVersion, currentVersion) > 0) {
// 需要更新
return true;
}
return false;
};
性能优化技巧
- 使用差分更新减少下载大小
- 在后台静默下载更新
- 预加载可能需要的资源
- 实现渐进式更新策略,优先加载关键补丁
通过以上方法,React Native 应用可以实现灵活的热更新功能,显著提升用户体验并加快迭代速度。






