用户3111234
用户3111234
  • 发布:34 分钟前
  • 更新:33 分钟前
  • 阅读:29

ArkTS中globalThis无法使用该如何替换

分类:uts

ArkTS不支持动态更改对象布局,也不支持全局作用域和globalThis。请参考以下替换方案:

通过单例map做中转:
import { common } from '@kit.AbilityKit';

// Construct singleton objects
export class GlobalThis {
private constructor() {};
private static instance: GlobalThis;
private _uiContexts = new Map<string, common.UIAbilityContext>();
private value = '';

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

getContext(key: string): common.UIAbilityContext | undefined {
return this._uiContexts.get(key);
}

setContext(key: string, value: common.UIAbilityContext): void {
this._uiContexts.set(key, value);
}

setValue(value:string){
this.value = value
}

getValue():string{
return this.value;
}
}
使用:
import { GlobalThis } from '../utils/globalThis';

@Entry
@Component
struct Index {
@State value: string = GlobalThis.getInstance().getValue();

build() {
Row() {
Column() {
Text(this.value)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button("setValue")
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
GlobalThis.getInstance().setValue("TEST");
})
Button("getValue")
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.value = GlobalThis.getInstance().getValue();
})
}
.width('100%')
}
.height('100%')
}
}
https://coub.com/view/swvzdggf5j
https://coub.com/view/ye4gd3sao0
https://coub.com/view/ghqk1es5kx
https://coub.com/view/03o4bd766v
https://coub.com/view/68m21drggj
https://coub.com/view/8thcb7i30k
https://coub.com/view/31riji8szs
https://coub.com/view/m5pl2o10xc
https://coub.com/view/7u092r3c3y
https://coub.com/view/9z16hl1l27
https://coub.com/view/2ah3o3gikc
https://coub.com/view/iw2if4xzmu
https://coub.com/view/nfxz1ptvwv
https://coub.com/view/tx87vhjgoa
https://coub.com/view/vyevukgqvm
https://coub.com/view/fthgsz7lnz
https://coub.com/view/b0ejxz86io
https://coub.com/view/dlhtg4x98h
https://coub.com/view/zhxtd2ao6o
https://coub.com/view/b9bm4phjml
https://coub.com/view/f1fj7h7m7n
https://coub.com/view/gqmubrlunk
https://coub.com/view/rsmf0pq0ep
https://coub.com/view/5osnlnz7m6
https://coub.com/view/myf9nili3g
https://coub.com/view/2q4qqmffiu
https://coub.com/view/4fdney7atb
https://coub.com/view/tlc5k72rnn
https://coub.com/view/qjtzu6sctg
https://coub.com/view/knhnvgqaav
https://coub.com/view/9tr096tibg
https://coub.com/view/sqngjncbpi
https://coub.com/view/5oi5uu3hdk
https://coub.com/view/feq4uge5zp
https://coub.com/view/gnjjd1jkh7
https://coub.com/view/ncepuxpw6s
https://coub.com/view/lgvpgf7owb
https://coub.com/view/5itb2jz3nn
https://coub.com/view/a27in0zzoi
https://coub.com/view/s90xkrewah
https://coub.com/view/krpqqdbks7
https://coub.com/view/g15onqg56s
https://coub.com/view/gjem8bpjq7
https://coub.com/view/vxzlg1bbx6
https://coub.com/view/uclkamqsye
https://coub.com/view/9ktk9y9rnp
https://coub.com/view/m3pukii96g
https://coub.com/view/ubjx0glwg2
https://coub.com/view/tq0q476sve
https://coub.com/view/6mq6jfkf8g
https://coub.com/view/skmrl4a5fr
https://coub.com/view/2btoisvnfc
https://coub.com/view/tdf9iyk9t8
https://coub.com/view/qtnb1vdhz8
https://coub.com/view/pgjbq68e29
https://coub.com/view/761mcrewbc
https://coub.com/view/9ywqd4gmue
https://coub.com/view/dahorqam08
https://coub.com/view/22f6pq75h1
https://coub.com/view/rx6soyay6y
https://coub.com/view/tkmakc1ydn
https://coub.com/view/qfwrpt5vf3
https://coub.com/view/jc7h45ztmv
https://coub.com/view/usm8o9f7vx
https://coub.com/view/1kd1sa2s8i
https://coub.com/view/80kw21uf7e
https://coub.com/view/nswxkfoj6p
https://coub.com/view/em9qqb0cji
https://coub.com/view/kfhozymvbu
https://coub.com/view/ryodtti0l0
https://coub.com/view/2wn8ui8z6r
https://coub.com/view/qae1djzkbo
https://coub.com/view/f2u6loev3s
https://coub.com/view/nf96gelk1m
https://coub.com/view/wx4w15u7rb
https://coub.com/view/9d163aq8wn
https://coub.com/view/ejwo7q5ztk
https://coub.com/view/4r153x56cy
https://coub.com/view/q58fw6nqsf
https://coub.com/view/97gf4yivg1
https://coub.com/view/ob3p4cw3lj
https://coub.com/view/syggoc7k9w
https://coub.com/view/28pfvj1zmn
https://coub.com/view/omj88cdnbq
https://coub.com/view/jqb8ofnoo3
https://coub.com/view/xbmf758zv9
https://coub.com/view/y8vxp930lx
https://coub.com/view/gcyhau8z0o
https://coub.com/view/x8xieqta3s
https://coub.com/view/9cqjaj9ehu

34 分钟前 负责人:无 分享
已邀请:
Ask小助手

Ask小助手 - Ask社区AI助手

欢迎到专业群( uni-app x技术交流群 ) 咨询,群中有相关专业的管理员和群友。

在 ArkTS 中由于不支持动态对象布局和 globalThis,推荐使用单例模式结合 Map 来实现全局状态管理。以下是完整的替换方案:

1. 创建全局单例类

// utils/GlobalThis.ets  
import { common } from '@kit.AbilityKit';  

export class GlobalThis {  
  private static instance: GlobalThis;  
  private _uiContexts = new Map<string, common.UIAbilityContext>();  
  private _values = new Map<string, Object>();  

  private constructor() {}  

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

  // Context 管理  
  setContext(key: string, context: common.UIAbilityContext): void {  
    this._uiContexts.set(key, context);  
  }  

  getContext(key: string): common.UIAbilityContext | undefined {  
    return this._uiContexts.get(key);  
  }  

  // 通用值存储  
  setValue(key: string, value: Object): void {  
    this._values.set(key, value);  
  }  

  getValue(key: string): Object | undefined {  
    return this._values.get(key);  
  }  

  removeValue(key: string): void {  
    this._values.delete(key);  
  }  

  clear(): void {  
    this._uiContexts.clear();  
    this._values.clear();  
  }  
}

本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码

2. 在页面中使用

// pages/Index.ets  
import { GlobalThis } from '../utils/GlobalThis';  

@Entry  
@Component  
struct Index {  
  @State value: string = '';  
  private globalThis = GlobalThis.getInstance();  

  aboutToAppear(): void {  
    // 初始化时获取值  
    const savedValue = this.globalThis.getValue('testKey');  
    if (savedValue) {  
      this.value = savedValue as string;  
    }  

    // 保存当前 Context  
    this.globalThis.setContext('index', getContext(this) as common.UIAbilityContext);  
  }  

  build() {  
    Column() {  
      Text(this.value)  
        .fontSize(50)  
        .fontWeight(FontWeight.Bold)  
        .margin(20)  

      Button('设置全局值')  
        .onClick(() => {  
          this.globalThis.setValue('testKey', 'Hello ArkTS');  
        })  

      Button('获取全局值')  
        .onClick(() => {  
          const val = this.globalThis.getValue('testKey');  
          this.value = val ? val.toString() : '空';  
        })  
    }  
    .width('100%')  
    .height('100%')  
    .justifyContent(FlexAlign.Center)  
  }  
}

本助手使用国产模型,生成代码准确率较低。强烈建议使用uni-agent生成代码

3. 关键优势

  • 类型安全:通过 Map 的泛型约束确保类型安全
  • 内存管理:提供 removeValueclear 方法避免内存泄漏
  • Context 隔离:支持多 Context 存储,适用于多窗口场景
  • 跨页面共享:单例模式确保数据在页面间共享

4. 注意事项

  1. 及时清理:页面销毁时调用 removeValue 清理不再需要的数据
  2. 避免滥用:不要存储大量数据或复杂对象,防止内存占用过高
  3. 线程安全:ArkTS 是单线程模型,无需担心并发问题
  4. 替代方案:对于简单全局状态,也可考虑使用 AppStorage 或 PersistentStorage

这种模式完全遵循 ArkTS 的强类型约束,同时提供了类似 globalThis 的全局访问能力,是官方推荐的最佳实践。

内容为 AI 生成,仅供参考

要回复问题请先登录注册