美文网首页
ReactNative AsyncStorage 工具类

ReactNative AsyncStorage 工具类

作者: 月落吖 | 来源:发表于2019-04-24 09:28 被阅读0次
  1. AsyncStorage 工具类
import { AsyncStorage }from 'react-native';

export default class IAsyncStorage {

    /**

    * 获取数据

    *

    * @param key

    * @returns {Promise<T>|*|Promise.<TResult>}

    */

    static get(key) {

        return AsyncStorage.getItem(key).then((value) => {

            let jsonValue = JSON.parse(value);

            return jsonValue;

        });

    }

    /**

    * 保存数据

    *

    * @param key

    * @param value

    * @returns {*}

    */

    static save(key, value) {

        return AsyncStorage.setItem(key, JSON.stringify(value));

    }

    /**

    * 更新数据

    *

    * @param key

    * @param value

    * @returns {Promise<T>|Promise.<TResult>}

    */

    static update(key, value) {

        return DeviceStorage.get(key).then((item) => {

            value = typeof value === 'string' ? value : Object.assign({}, item, value);

            return AsyncStorage.setItem(key, JSON.stringify(value));

        });

    }

    /**

    * 删除数据

    * @param key

    * @returns {*}

    */

    static delete(key) {

        return AsyncStorage.removeItem(key);

    }

    /**

    * 获取多条数据

    *

    * @param {*} arr

    */

    static getMulti(arr){

        return AsyncStorage.multiGet(arr)

            .then(stores =>{

                let value = [];

                stores.map((result, i, store) => {

                value.push(JSON.parse(store[i][1]));

                })

                return value;

            })

    }

    /**

    * 获取索引集合

    */

    static getKeys(){

        return AsyncStorage.getAllKeys();

    }

    /**

    * 删除多条数据

    *

    * @param {*} arr

    */

    static deleteMulti(arr){

        return AsyncStorage.multiRemove(arr);

    }

    /**

    * 清除

    */

    static clear(){

        return AsyncStorage.clear();

    }

}
  1. 使用说明
  IAsyncStorage.save('person1',{

      name: '张三',

      age: 18,

      sex: '男'

    })

    .then(res =>{

      if(!res){

        console.log('save success');

      }

    })

      IAsyncStorage.getMulti(['person1','person2'])

        .then(value =>{

          console.log(value)

        })
      IAsyncStorage.getKeys()

        .then(res =>{

          console.log(res);

        })

相关文章

网友评论

      本文标题:ReactNative AsyncStorage 工具类

      本文链接:https://www.haomeiwen.com/subject/bnkwgqtx.html