如果現在有一個需求,是要把用戶的賬號密碼保存到本地,大家會怎么做的呢?如果在android中,我相信一大部分人會想到SharedPreferences,這是一個以鍵值對的形式進行存儲的。那如果在react native中呢,有沒有一個像SharedPreferences一樣的輕量存儲器呢?答案是有的---AsyncStorage。
AsyncStorage是一個簡單的、異步的、持久化的Key-Value存儲系統,它對於App來說是全局性的。這是官網上對它的介紹。可以知道,這個asyncstorage也是以鍵值對的形式進行存儲數據的。
那么問題來了,該怎么使用這個呢?官網上說並不推薦我們直接用這個asyncstorage,而是進行抽象封裝以后在進行調用。首先看一看我在項目中的用法。
上代碼:
1 import React, { 2 AsyncStorage 3 }from 'react-native'; 4 5 class DeviceStorage { 6 /** 7 * 獲取 8 * @param key 9 * @returns {Promise<T>|*|Promise.<TResult>} 10 */ 11 12 static get(key) { 13 return AsyncStorage.getItem(key).then((value) => { 14 const jsonValue = JSON.parse(value); 15 return jsonValue; 16 }); 17 } 18 19 20 /** 21 * 保存 22 * @param key 23 * @param value 24 * @returns {*} 25 */ 26 static save(key, value) { 27 return AsyncStorage.setItem(key, JSON.stringify(value)); 28 } 29 30 31 /** 32 * 更新 33 * @param key 34 * @param value 35 * @returns {Promise<T>|Promise.<TResult>} 36 */ 37 static update(key, value) { 38 return DeviceStorage.get(key).then((item) => { 39 value = typeof value === 'string' ? value : Object.assign({}, item, value); 40 return AsyncStorage.setItem(key, JSON.stringify(value)); 41 }); 42 } 43 44 45 /** 46 * 更新 47 * @param key 48 * @returns {*} 49 */ 50 static delete(key) { 51 return AsyncStorage.removeItem(key); 52 } 53 } 54 55 export default DeviceStorage;
可以看到asyncstorage中存在有更刪改查這些方法,當然,上面是把asyncstorage進行了封裝,在其他地方調用的時候就可以作為一個工具進行調用了。
調用方式:
1 //appHotSearchTagList就是當時保存的時候所保存的key,而tags就是保存的值 2 3 Storage.get('appHotSearchTagList').then((tags) => { 4 this.setState({ 5 tags: tags 6 }) 7 });
這里我只是貼出了一種獲取數據的方式,其實另外的更新,刪除,保存,方式都是差不多。