react-native系列(18)API篇:AsyncStorage数据持久化

本文深入探讨了AsyncStorage在应用中的数据持久化作用,详细介绍了存储、获取、移除和合并数据的操作方法,包括单一数据和批量数据的处理方式,并提供了实际代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据持久化是指使用AsyncStorage模块存储了数据后,即使关闭了app,只要下次打开依然可以读取到已存储的数据,它包含4个操作:存储、获取、移除和合并,存储数据的方式是Map存储,即(key, value)。另外,无论是key还是value都只支持字符串格式,其它格式将会报错(如果要存储对象格式的数据,可以通过JSON.stringify先把对象转化为字符串格式)。

单一数据操作

封装好的方法如下:

// 存储
_storeData = async (key, value) => {
    try {
        await AsyncStorage.setItem(key, value);
        console.log('保存成功');
    } catch (error) {
        console.log('保存失败');
    }
}

// 获取,注意: async定义的函数返回值类型为Promise
_retrieveData = async (key) => {
    try {
        const value = await AsyncStorage.getItem(key);
        if (value !== null) {
            console.log('获取成功');
            return value;
        }else{
            console.log('获取失败');
            return null;
        }
    } catch (error) {
        console.log('获取失败');
    }
}

// 移除
_removeData = async (key) => {
    try {
        await AsyncStorage.removeItem(key);
        console.log('移除成功');
    } catch (error) {
        console.log('移除失败');
    }
}

// 合并,仅限于对象格式字符串
_mergeData = async (key, value) => {
    try {
        await AsyncStorage.mergeItem(key, value);
        console.log('合并成功');
    } catch (error) {
        console.log('合并失败');
    }
}

使用:存储、获取

this._storeData('name','John');
this._retrieveData('name').then((response)=>{
    console.log(response); // John
});

使用:合并

const object1 = {
    sex: 'man',
    age: 30,
    hair: 'blue'
};
const object2 = {
    sex: 'man',
    age: 32,
    hair: 'yellow'
};
this._retrieveData('user').then((resp)=>{
    console.log('json:', resp); // undefined
}); 
this._storeData('user',JSON.stringify(object1));
this._retrieveData('user').then((resp)=>{
    console.log('json:', resp); // {"sex":"man","age":30,"hair":"blue"}
}); 
this._mergeData('user',JSON.stringify(object2));
this._retrieveData('user').then((resp)=>{
    console.log(resp); // {"sex":"man","age":32,"hair":"yellow"}
});

批量数据操作

在批量操作时,数据通过二维数组的格式来组装。如在存储和合并时使用[['id', '1'], ['name', 'John']],在获取和移除时使用['id', 'name']。

封装好的方法如下:

// 批量存储
_multiStoreData = async (keyValuePairs) => {
    try {
        await AsyncStorage.multiSet(keyValuePairs);
        console.log('批量保存成功');
    } catch (error) {
        console.log('批量保存失败');
    }
}

// 批量获取
_multiRetrieveData = async (keyArray) => {
    try {
        const value = await AsyncStorage.multiGet(keyArray);
        if (value !== null) {
            console.log('批量获取成功');
            return value;
        }else{
            console.log('批量获取失败');
            return null;
        }
    } catch (error) {
        console.log('批量获取失败');
        return null;
    }
}

// 批量移除
_multiRemoveData = async (keyArray) => {
    try {
        await AsyncStorage.multiRemove(keyArray);
        console.log('批量移除成功');
    } catch (error) {
        console.log('批量移除失败');
    }
}

// 批量合并
_multiMergeData = async (keyValuePairs) => {
    try {
        await AsyncStorage.multiMerge(keyValuePairs);
        console.log('批量合并成功');
    } catch (error) {
        console.log('批量合并失败');
    }
}

使用:

this._multiStoreData([['multi1','value1'],['multi2','value2'],['multi3','value3']]);
this._multiRetrieveData(['multi1','multi3']).then((resp)=>{
    console.log(resp); // 打印结果 [['multi1','value1'],['multi3','value3']]
});

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值