
文章目录前言GlobalContext 是什么写入put 和 setObject读取get 和 getObjecthas检查 Key 是否存在remove移除指定 Keyclear清空所有缓存综合演示模拟登录状态管理GlobalContext vs AppStorage怎么选写在最后前言近期发现一款很有意思的HarmonyOS 三方库, 地址 pura/harmony-utils(V1.4.0) , 作者是桃花镇童长老, 我这里也是直接通过该作者公布的源码进行案例编写进行,写了到目前写了一部分demo ,感觉确实很有帮助,这里呢也是开始写一个系列的演示demo 供大家参考。如有帮助可以在OpenHarmony中进行下载安装进行使用哦案例demo导航展示↓↓↓↓↓↓接下来言归正传 ↓↓↓↓写 HarmonyOS App很快就会遇到一个问题登录成功后token 存在哪其他页面怎么拿路由传参只能传一次AppStorage有绑定 UI 的额外开销很多时候你就想要个简单的全局 HashMap——存进去随时取谁都能用。GlobalContext就是这个东西。GlobalContext 是什么GlobalContext是一个应用级别的单例 Key-Value 缓存本质上就是一个Mapstring, Object。它的特点单例整个应用只有一个实例所有页面共享类型安全支持泛型取值取出来的类型可以直接用轻量没有响应式、没有 UI 绑定就是纯粹的键值存储演示代码里的描述Column({space:4}){Text(GlobalContext 是应用全局单例 Key-Value 缓存).fontSize(13).fontColor(#555)Text(支持跨页面、跨组件传递任意 Object 数据).fontSize(12).fontColor(#888)}写入put 和 setObject// put写入任意类型GlobalContext.getContext().put(this.inputKey,this.inputValue);this.addLog(put(${this.inputKey}, ${this.inputValue}));// setObject功能一样名字不同GlobalContext.getContext().setObject(this.inputKey,this.inputValue);this.addLog(setObject(${this.inputKey}, ${this.inputValue}));put和setObject功能完全等同语义略有差别按习惯选一个用就好。写入数字类型GlobalContext.getContext().put(timestamp,Date.now());this.addLog(put(timestamp,${Date.now()}));写入对象类型// 先定义 interfaceinterfaceUserInfo{name:string;age:number;roles:string[];}// 再写入constobj:UserInfo{name:若城,age:18,roles:[admin,user]};GlobalContext.getContext().put(userInfo,obj);this.addLog(put(userInfo,${JSON.stringify(obj)}));GlobalContext 的值类型是Object所以可以存任意类型。读取get 和 getObject// getT泛型取值返回 T 类型constvalGlobalContext.getContext().getstring(this.inputKey);this.getResultval!undefined?String(val):(undefined);this.addLog(get(${this.inputKey}) →${this.getResult});// getObject不带泛型返回 ObjectconstvalGlobalContext.getContext().getObject(this.inputKey);this.addLog(getObject(${this.inputKey}) →${val!undefined?String(val):undefined});getT带泛型更推荐因为取出来的值直接是对应类型不需要强转。取数字consttsGlobalContext.getContext().getnumber(timestamp);this.addLog(getnumber(timestamp) →${ts});取对象constinfoGlobalContext.getContext().getobject(userInfo);this.addLog(get(userInfo) →${info?JSON.stringify(info):undefined});注意如果 key 不存在get返回undefined使用前要判断是否 undefined不然直接访问属性会空指针崩溃。has检查 Key 是否存在constresultGlobalContext.getContext().has(this.inputKey);this.hasResultresult?存在:不存在;this.addLog(has(${this.inputKey}) →${result});// 检查不存在的 keyconstrGlobalContext.getContext().has(notExistKey);this.addLog(has(notExistKey) →${r});// 结果false在读取数据前用has判断 key 是否存在是个好习惯if(GlobalContext.getContext().has(token)){consttokenGlobalContext.getContext().getstring(token);// 安全使用 token}remove移除指定 Key// 移除单个 keyGlobalContext.getContext().remove(this.inputKey);this.addLog(remove(${this.inputKey}) 已移除);// 移除后验证GlobalContext.getContext().remove(this.inputKey);constrGlobalContext.getContext().has(this.inputKey);this.addLog(remove后 has(${this.inputKey}) →${r});// 结果falseclear清空所有缓存GlobalContext.getContext().clear();this.addLog(clear() 已清空所有缓存);// 清空后验证GlobalContext.getContext().clear();constr1GlobalContext.getContext().has(this.inputKey);constr2GlobalContext.getContext().has(userInfo);this.addLog(clear后 has(${this.inputKey}) →${r1});this.addLog(clear后 has(userInfo) →${r2});// 结果都是 falseclear适合在退出登录时调用一次性清除所有用户相关的全局状态。综合演示模拟登录状态管理演示代码里有一段完整的登录状态模拟非常实用模拟登录后存储数据GlobalContext.getContext().put(isLogin,true);GlobalContext.getContext().put(token,Bearer eyJhbGci.example);GlobalContext.getContext().put(userName,全栈若城);GlobalContext.getContext().put(userId,10086);this.addLog(已存储登录信息: isLogin/token/userName/userId);模拟其他页面读取登录状态constisLoginGlobalContext.getContext().getboolean(isLogin);constnameGlobalContext.getContext().getstring(userName);constidGlobalContext.getContext().getnumber(userId);this.addLog(isLogin:${isLogin}name:${name}userId:${id});模拟退出登录GlobalContext.getContext().clear();constisLoginGlobalContext.getContext().getboolean(isLogin);this.addLog(退出后 isLogin:${isLogin});// 结果undefined这三步代码展示了 GlobalContext 的完整生命周期登录存数据、使用时读数据、退出时清数据。GlobalContext vs AppStorage怎么选特性GlobalContextAppStorage响应式❌✅UI 双向绑定❌✅轻量级✅✅适合存非 UI 数据✅不推荐适合存 token、userId✅一般用全局变量简单原则需要 UI 自动更新的数据用State/AppStorage不需要 UI 响应的全局数据token、配置、用户信息用GlobalContext。写在最后GlobalContext 的 API 很简单就四组put/setObject写数据getT/getObject读数据推荐用泛型版has判断 key 是否存在remove/clear删除单个或全部适合存的东西token、用户 ID、全局配置、应用上下文对象。不适合存的需要 UI 响应的状态数据那个用State或AppStorage。