数据持久化是指使用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']]
});