React Native Expo如何替代已废弃的Constants.installationId
落地操作全步骤
1. 安装所需依赖
在项目根目录执行以下命令安装适配你当前Expo版本的依赖包:npx expo install expo-application expo-secure-store
2. 封装跨平台唯一ID工具函数
新建工具文件比如src/utils/installationId.js,写入以下代码:
import * as Application from 'expo-application'; import * as SecureStore from 'expo-secure-store'; import { Platform } from 'react-native'; // 自定义存储键名,避免和项目其他存储内容冲突 const INSTALLATION_ID_STORAGE_KEY = 'app_unique_installation_id'; export async function getInstallationId() { // 安卓端直接调用expo-application提供的原生androidId if (Platform.OS === 'android') { return Application.androidId; } // iOS端从安全存储读取,不存在则生成UUID后存储再返回 if (Platform.OS === 'ios') { const existedId = await SecureStore.getItemAsync(INSTALLATION_ID_STORAGE_KEY); if (existedId) return existedId; const newId = crypto.randomUUID(); await SecureStore.setItemAsync(INSTALLATION_ID_STORAGE_KEY, newId); return newId; } // Web端从localStorage读取,不存在则生成UUID后存储再返回 if (Platform.OS === 'web') { const existedId = window.localStorage.getItem(INSTALLATION_ID_STORAGE_KEY); if (existedId) return existedId; const newId = crypto.randomUUID(); window.localStorage.setItem(INSTALLATION_ID_STORAGE_KEY, newId); return newId; } }
3. 替换原有废弃API调用
将项目中所有使用Constants.installationId的代码替换为调用上述封装的工具函数即可,示例:
原代码写法
import Constants from 'expo-constants'; const reportUserBehavior = () => { const userId = Constants.installationId; // 后续业务逻辑 }
修改后写法
import { getInstallationId } from '@/utils/installationId'; const reportUserBehavior = async () => { const userId = await getInstallationId(); // 原有业务逻辑完全不变 }
注意:因为工具函数是异步方法,需要在async函数中调用,或者通过.then()链式调用
4. 验证修改效果
- 执行
npx expo start重启开发服务,原有的Constants.installationId弃用警告将消失 - 安卓端:多次重启应用ID保持一致,卸载重装后ID更新
- iOS端:重启应用、升级系统后ID保持一致,卸载重装后ID更新
- Web端:不清除浏览器缓存时ID保持一致,清除缓存后ID更新
可选优化项
- 若项目运行环境不支持
crypto.randomUUID,可安装uuid库替代:执行npx expo install uuid,将生成ID的代码替换为import { v4 as uuidv4 } from 'uuid'; const newId = uuidv4(); - 若不需要iOS端ID跟随iCloud备份同步,存储时添加参数关闭同步:
await SecureStore.setItemAsync(INSTALLATION_ID_STORAGE_KEY, newId, { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY })
内容的提问来源于stack exchange,提问作者Rashid Rcp
相关产品推荐
相关产品推荐

