LocalStorage传递Function HarmonyOS 鸿蒙Next

LocalStorage传递Function HarmonyOS 鸿蒙Next 咨询场景描述:LocalStorage传递Function 出现Error message:@Component ‘owning @Component UNKNOWN’: Illegal variable value error with decorated variable undefined ‘clickSend’: failed validation: 'undefined, null, number, boolean, string, or Object but not function, not V2 @ObservedV2 / @Trace class, and makeObserved return value either, attempt to assign value type: ‘function’, value: ‘undefined’!


更多关于LocalStorage传递Function HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

暂无LocalStorage直接存储Function类型。可以尝试使用json去传递。

更多关于LocalStorage传递Function HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next中,LocalStorage 是一个用于页面间数据传递的机制。LocalStorage 可以存储和传递基本数据类型、对象以及数组,但不直接支持传递函数。如果需要传递函数,可以通过将函数转换为字符串形式存储,然后在目标页面中重新解析为函数。

例如,可以使用 JSON.stringify 将函数转换为字符串存储在 LocalStorage 中,然后在目标页面中使用 JSON.parseeval 将其还原为函数。需要注意的是,eval 的使用存在安全风险,应确保数据来源可信。

// 存储函数
const func = () => console.log("Hello, HarmonyOS");
LocalStorage.set({ key: 'myFunction', value: JSON.stringify(func) });

// 读取并执行函数
const funcString = LocalStorage.get<string>('myFunction');
if (funcString) {
  const func = eval(`(${funcString})`);
  func();
}

此外,鸿蒙Next还提供了 EventHubEmitter 等机制用于跨页面通信,可以考虑使用这些机制来传递函数或触发特定行为。

回到顶部