AppStorage.get 拿到的值undefined
·
随身WiFi相关(程序+源码+工具+调试部署+开发环境)包含4G/5G/CPE设备,总共500多GB以上,文章末尾可获取,在最后面了。
在HarmonyOS中,AppStorage 是一个用于存储应用数据的API。如果你在组件A中设置了一个值,但在组件B中获取该值时总是得到 undefined,可能有以下几种原因:
- Key不一致:确保你在组件A和组件B中使用的key完全一致。如果用户ID (
this.memberInfo.member_id) 不同,那么生成的key也会不同,导致无法正确获取到之前存储的值。 - 异步问题:确保在组件B中获取数据时,组件A已经成功设置了数据。如果组件B在组件A设置数据之前就尝试获取数据,可能会得到
undefined。 - 数据类型不匹配:确保你存储的数据类型和获取的数据类型一致。虽然你使用的是泛型
<string>,但仍然需要确认实际存储的数据确实是字符串。 - 缓存问题:有时候缓存机制可能会导致数据读取失败。可以尝试清除缓存或者重启应用来排除这个问题。
- 权限问题:确保你的应用有读写存储的权限。
以下是一些调试步骤和代码示例:
调试步骤
- 检查Key一致性:
- 确保
this.memberInfo.member_id 在组件A和组件B中是相同的。 - 打印出key,确保它们确实相同。
// 组件A
let key: string = `user_switch_status_${this.memberInfo.member_id}`;
console.log('Component A Key:', key);
AppStorage.setOrCreate(key, this.recommendType ? 'open' : 'close');
// 组件B
let key: string = `user_switch_status_${this.memberInfo.member_id}`;
console.log('Component B Key:', key);
let checkType = AppStorage.get<string>(key);
console.log('AppStorage user_recommend_status', checkType);
- 确保顺序正确:
- 确保组件A在组件B之前执行,并且数据已经被设置。
- 检查数据类型:
- 确保存储的数据确实是字符串类型。
示例代码
组件A
import { AppStorage } from '@ohos/application';
export default {
data() {
return {
memberInfo: { member_id: '12345' }, // 示例用户ID
recommendType: true // 示例推荐类型
};
},
methods: {
setUserSwitchStatus() {
let key: string = `user_switch_status_${this.memberInfo.member_id}`;
console.log('Component A Key:', key);
AppStorage.setOrCreate(key, this.recommendType ? 'open' : 'close');
}
},
mounted() {
this.setUserSwitchStatus();
}
};
组件B
import { AppStorage } from '@ohos/application';
export default {
data() {
return {
memberInfo: { member_id: '12345' } // 示例用户ID
};
},
methods: {
getUserSwitchStatus() {
let key: string = `user_switch_status_${this.memberInfo.member_id}`;
console.log('Component B Key:', key);
let checkType = AppStorage.get<string>(key);
console.log('AppStorage user_recommend_status', checkType);
}
},
mounted() {
this.getUserSwitchStatus();
}
};
通过以上步骤和代码示例,你应该能够找到问题所在并解决 AppStorage.get 返回 undefined 的问题。
4G/5G/CPE/随身WiFi刷机程序+工具资源,获取方式↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
更多推荐



所有评论(0)