-
-
- 簡介
- 常用API
- 讀取資料
- 寫入資料
- 删除資料
- 更多API
- 儲存目錄
- iOS端
- Android
- 使用執行個體
- 異步存儲資料
- 異步讀取資料
- 異步删除某條資料
- 異步删除所有資料
- 同步讀取資料
- 同步存儲資料
- 在原生代碼中擷取存儲的資料
-
簡介
AsyncStorage是一個簡單的、異步的、持久化的Key-Value存儲系統,它對于App來說是全局性的。
在真正使用的過程中建議在AsyncStorage的基礎上做一層抽象封裝,而不是直接使用AsyncStorage。
推薦由React Native中文網封裝維護的react-native-storage子產品,提供了較多便利功能。
常用API
1. 讀取資料
//讀取key字段并将結果作為第二個參數傳遞給callback
static getItem(key: string, callback?: ?(error: ?Error, result: ?string) => void)
//擷取keys所包含的所有字段的值,調用callback回調函數時傳回一個key-value數組形式的數組
static multiSet(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void)
2. 寫入資料
将key字段的值設定成value,并在完成後調用callback函數。如果有任何錯誤發生,則會傳遞一個Error對象作為第一個參數。傳回一個Promise對象。
//寫入一個資料
static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)
//寫入一組資料(key-value數組)
static multiSet(keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void)
3. 删除資料
删除一個字段。傳回一個Promise對象。
static removeItem(key: string, callback?: ?(error: ?Error) => void)
删除所有鍵在keys數組中的資料。傳回一個Promise對象。
static multiRemove(keys: Array<string>, callback?: ?(errors: ?Array<Error>) => void)
删除全部的AsyncStorage資料,傳回一個Promise對象。
…更多API
儲存目錄
iOS端
iOS 端儲存目錄: Documents 目錄下的RCTAsyncLocalStorage_XXX/manifest.json 檔案,儲存的文檔實質就是個json 文本
//在原生代碼中擷取Documents目錄路徑
NSArray *paths_Documents =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths_Documents objectAtIndex:];
使用模拟器調試應用 ,使用上訴代碼輸出Documents檔案目錄 ,點選mac 最上方的菜單欄的前往->前往檔案夾 輸入獲得的目錄 ,即可跳轉到該目錄下可找到上面的檔案。
Android
暫時略
使用執行個體
異步存儲資料
異步存儲 一條資料
let userInfor = {email:'[email protected]',name:'xxx',age:};
const tableKey = 'XXX-XXXX_TableKey';
AsyncStorage.setItem(tableKey, JSON.stringify(userInfor), function(err){
if (err) {
//console.log('__storageUserItem:(error)'+err);
return;
}
//console.log('__storage:(success)' + userInfor.email);
});
異步存儲多條資料
let userInfor = {email:'[email protected]',name:'xxx',age:};
AsyncStorage.multiSet(userInfor, function(err){
if (err&&err.length>) {
//console.log('__storageUserItem:(error),出錯條數數:'+err.length);
return;
}
//console.log('__storage:(success)' + userInfor.email);
});
注意以上寫法的差別,儲存在檔案具體差別是什麼。
1.第一種
是将userInfor 做為一整條資料 存儲到檔案中對應的鍵值 tableKey 上.即:
2.第二種
是将userInfor 做為key-value 多條資料 存儲到檔案中,如:
異步讀取資料
AsyncStorage.getItem(tableKey, function(err, result) {
if (err) {
//console.log('AsyncStorage.getItem error'+err);
return;
}
//console.log('AsyncStorage.getItem success'+JSON.parse(result));
return JSON.parse(result);
});
異步删除某條資料
AsyncStorage.removeItem(key,function(err) {
if (err) {
//console.log('__removeItem:'+err);
}
//TODO:other
});
異步删除所有資料
AsyncStorage.clear(key,function(err) {
if (err) {
//console.log('__clearStorage:'+err);
}
//TODO:other
});
同步讀取資料
這個使用場景也蠻多的 ,通過擷取的資料來判斷進入哪個界面或者進一步做什麼事,從功能邏輯上必須有先後,這時需要等到擷取資料後才能進行下一步操作。
如:免登入功能 ,如果使用者已經登入過(沒有點選退出)下次啟動APP時直接進入首頁面,如果已經退出或第一次使用則進入登入頁面。
componentWillMount(){
this._loadStorage();
}
async _loadStorage() {
let _that = this;
try {
let useReadability = await AsyncStorage.getItem(userInforIsLogin_tableKey);
if (useReadability !== null) {
const userInfor = JSON.parse(useReadability) ;
//console.log('(AsyncStorage.getItem) success'+userInfor.email);
if (userInfor.token!=null) { //根據token 或其它标志來判斷
//TODO 說明是登入狀态,進入首頁面
return;
}
}
//TODO 進入登入頁面
} catch(e) {
console.log('_loadStorage error'+e);
//TODO 進入登入頁面
}
}
同步存儲資料
…略
在原生代碼中擷取存儲的資料
在原生代碼中 ,擷取檔案裡面的内容(下面是oc 代碼)
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* thepath = [paths lastObject];
thepath = [thepath stringByAppendingPathComponent:@"RCTAsyncLocalStorage_V1/manifest.json"];
NSLog(@"目錄:%@", thepath);
//第一種方法: NSFileManager執行個體方法讀取資料
NSFileManager* fm = [NSFileManager defaultManager];
NSData* data = [[NSData alloc] init];
data = [fm contentsAtPath:thepath];
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//第二種方法: NSData類方法讀取資料
data = [NSData dataWithContentsOfFile:thepath];
NSLog(@"NSData類方法讀取的内容是:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//第三種方法: NSString類方法讀取内容
NSString* content = [NSString stringWithContentsOfFile:thepath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"NSString類方法讀取的内容是:\n%@",content);