uni-app uni.getStorage代码块中循环增加值给数组 一直为空 无法完成赋值给数组
uni-app uni.getStorage代码块中循环增加值给数组 一直为空 无法完成赋值给数组
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win10 | HBuilderX |
产品分类:uniapp/App
PC开发环境操作系统:Windows
PC开发环境操作系统版本号:win10
HBuilderX类型:正式
HBuilderX版本号:3.4.7
手机系统:Android
手机系统版本号:Android 12
手机厂商:华为
手机机型:华为荣耀9X
页面类型:vue
vue版本:vue3
打包方式:云端
示例代码:
get_see2(){
for(var c=0;c<this.mdatas.length;c++){
uni.getStorage({
key: 'pic'+this.id+c,
success:(res) =>{
console.log(res.data.length+res.data.slice(0,10)+'单张图片缓存已存在');
let bd_url = res.data;
//console.log(res.data);
if(res.data.slice(0,10).indexOf('_doc')>=0){
console.log('本地图片,转绝对路径!');
bd_url ='file://'+plus.io.convertLocalFileSystemURL(res.data);
}
this.xinxi = '缓存';
this.see3.push(bd_url);
},
fail:(res)=>{
console.log('单张图片'+a+'缓存不存在'+res);
this.see3.push(this.mdatas[a]);
}
});
}
}
操作步骤:
- 获取网络地址this.mdatas数组长度,根据长度,确定storage中key的索引。
- 根据索引依次取出存储在storage的对应的本地地址,并赋值给新的数组this.see3
预期结果:
赋值成功
实际结果:
赋值失败,this.see3一直是空的。
bug描述:
循环取得网络地址数组this.mdatas中对应的存储在storage 相应KEY中的本地地址,并生成本地地址数组this.see3,this.see3.push增加值一直是空的,整个循环下来,uni.getStorage取值正常,但是取出来的值赋值就失败了。
在使用 uni.getStorage
获取数据并尝试将其赋值给数组时,如果发现数组一直为空,可能是由于异步操作导致的。uni.getStorage
是一个异步方法,因此在获取数据之前,代码可能已经继续执行了后续的逻辑,导致数组没有被正确赋值。
以下是一个示例代码,展示如何在 uni.getStorage
中正确地将数据赋值给数组:
// 假设我们有一个存储的键名
const storageKey = 'myData';
// 定义一个空数组
let myArray = [];
// 使用 uni.getStorage 获取数据
uni.getStorage({
key: storageKey,
success: function (res) {
// 获取到数据后,将其赋值给数组
myArray = res.data;
console.log('数据已成功赋值给数组:', myArray);
},
fail: function (err) {
console.error('获取数据失败:', err);
}
});
// 注意:由于 uni.getStorage 是异步的,这里的 myArray 可能还没有被赋值
console.log('当前数组:', myArray); // 这里可能还是空数组
解决方法
-
在
success
回调中处理数据:确保在success
回调中对数据进行处理,而不是在uni.getStorage
调用之后立即处理。 -
使用
async/await
:如果你使用的是支持async/await
的环境,可以将uni.getStorage
封装成一个返回Promise
的函数,然后使用await
来等待数据获取完成。
function getStorageAsync(key) {
return new Promise((resolve, reject) => {
uni.getStorage({
key: key,
success: (res) => resolve(res.data),
fail: (err) => reject(err)
});
});
}
async function fetchData() {
const storageKey = 'myData';
let myArray = [];
try {
myArray = await getStorageAsync(storageKey);
console.log('数据已成功赋值给数组:', myArray);
} catch (err) {
console.error('获取数据失败:', err);
}
console.log('当前数组:', myArray); // 这里应该已经赋值
}
fetchData();
- 确保数据已存储:在调用
uni.getStorage
之前,确保数据已经通过uni.setStorage
存储到本地。
uni.setStorage({
key: 'myData',
data: [1, 2, 3],
success: function () {
console.log('数据存储成功');
}
});