• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript react-native.AsyncStorage类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中react-native.AsyncStorage的典型用法代码示例。如果您正苦于以下问题:TypeScript AsyncStorage类的具体用法?TypeScript AsyncStorage怎么用?TypeScript AsyncStorage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了AsyncStorage类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: getCacheCurSize

  /**
   * return the current size of the cache
   * @return {Promise}
   */
  async getCacheCurSize() {
    let ret = await AsyncStorage.getItem(this.cacheCurSizeKey);
    if (!ret) {
      await AsyncStorage.setItem(this.cacheCurSizeKey, '0');
      ret = '0';
    }
    return Number(ret);

  }
开发者ID:lukethompson,项目名称:aws-amplify,代码行数:13,代码来源:AsyncStorageCache.ts


示例2: _removeItem

  /**
   * delete item from cache
   * @private
   * @param prefixedKey - the key of the item
   * @param size - optional, the byte size of the item
   */
  async _removeItem(prefixedKey, size?) {
    const itemSize = size? size : (JSON.parse(await AsyncStorage.getItem(prefixedKey))).byteSize;
    // first try to update the current size of the cache
    await this._decreaseCurSizeInBytes(itemSize);

    // try to remove the item from cache
    try {
      await AsyncStorage.removeItem(prefixedKey);
    } catch (removeItemError) {
      // if some error happened, we need to rollback the current size
      await this._increaseCurSizeInBytes(itemSize);
      logger.error(`Failed to remove item: ${removeItemError}`);
    }
  }
开发者ID:lukethompson,项目名称:aws-amplify,代码行数:20,代码来源:AsyncStorageCache.ts


示例3: _popOutItems

  /**
   * get all the items we have, sort them by their priority,
   * if priority is same, sort them by their last visited time
   * pop out items from the low priority (5 is the lowest)
   * @private
   * @param keys - all the keys in this cache
   * @param sizeToPop - the total size of the items which needed to be poped out
   */
  async _popOutItems(keys, sizeToPop) {
    const items = [];
    let remainedSize = sizeToPop;
    for (let i = 0; i < keys.length; i += 1) {
      const val = await AsyncStorage.getItem(keys[i]);
      if (val != null) {
        const item = JSON.parse(val);
        items.push(item);
      }
    }

    // first compare priority
    // then compare visited time
    items.sort((a, b) => {
      if (a.priority > b.priority) {
        return -1;
      } else if (a.priority < b.priority) {
        return 1;
      } else {
        if (a.visitedTime < b.visitedTime) {
          return -1;
        } else return 1;
      }
    });

    for (let i = 0; i < items.length; i += 1) {
      // pop out items until we have enough room for new item
      await this._removeItem(items[i].key, items[i].byteSize);
      remainedSize -= items[i].byteSize;
      if (remainedSize <= 0) {
        return;
      }
    }

  }
开发者ID:lukethompson,项目名称:aws-amplify,代码行数:43,代码来源:AsyncStorageCache.ts


示例4: finalizeLogIn

 /**
  * this should be called when the setup procedure has been successful
  * @param userId
  * @returns {*|Promise.<TResult>}
  */
 finalizeLogIn(userId) {
   // write to database that we are logged in.
   return AsyncStorage.setItem(LOGGED_IN_USER_ID_STORAGE_KEY, userId)
     .catch((err) => {
       LOGe.store("StoreManager: finalize login failed. ", err);
     })
 }
开发者ID:crownstone,项目名称:CrownstoneApp,代码行数:12,代码来源:storeManager.ts


示例5: _init

 _init() {
   AsyncStorage.getItem(this.userIdentificationStorageKey) // this will just contain a string of the logged in user.
     .then((userId) => {
       this._initializeStore(userId);
     })
     .catch((err) => { LOGe.store("StoreManager: Could not get store from AsyncStorage", err)});
 }
开发者ID:crownstone,项目名称:CrownstoneApp,代码行数:7,代码来源:storeManager.ts


示例6: flow

    hydrate: flow(function* () {

      if (__DEV__) {
        // Inspect individual models
        makeInspectable(self);
        makeInspectable(Movies);
        makeInspectable(InTheaters);
        makeInspectable(Genres);
      }

      const storageKey = 'Store.settings';
      const data = JSON.parse(yield AsyncStorage.getItem(storageKey));
      if (data) {
        applySnapshot(self.settings, data);
      }

      onSnapshot(self.settings, debounce(
        snapshot => AsyncStorage.setItem(storageKey, JSON.stringify(snapshot)),
        1200,
      ));

      // Load all supplimental data
      Genres.loadAllGenres();
      Cinemas.loadAllCinemas();

      self.isHydrated = true;
    }),
开发者ID:birkir,项目名称:kvikmyndr-app,代码行数:27,代码来源:index.ts


示例7: _isExpired

 /**
  * check wether item is expired
  * @private
  * @param key - the key of the item
  * 
  * @return true if the item is expired.
  */
 async _isExpired(key) {
   const text = await AsyncStorage.getItem(key);
   const item = JSON.parse(text);
   if (getCurrTime() >= item.expires) {
     return true;
   }
   return false;
 }
开发者ID:lukethompson,项目名称:aws-amplify,代码行数:15,代码来源:AsyncStorageCache.ts


示例8: setConsent

  public setConsent(consent: IDataPolicyConsent) {
    const serializedProgress = JSON.stringify(consent);

    return AsyncStorage.setItem(
      DataPolicyConsentStorage.getKey(),
      serializedProgress
    );
  }
开发者ID:serlo-org,项目名称:serlo-abc,代码行数:8,代码来源:DataPolicyConsentStorage.ts


示例9: getProgress

  public getProgress(id: string) {
    return AsyncStorage.getItem(this.getKey(id)).then(data => {
      if (!data) {
        return {};
      }

      return JSON.parse(data) as ISerializedProgress;
    });
  }
开发者ID:serlo-org,项目名称:serlo-abc,代码行数:9,代码来源:ProgressStorage.ts


示例10: setItem

  /**
   * Set item into cache. You can put number, string, boolean or object.
   * The cache will first check whether has the same key.
   * If it has, it will delete the old item and then put the new item in
   * The cache will pop out items if it is full
   * You can specify the cache item options. The cache will abort and output a warning:
   * If the key is invalid
   * If the size of the item exceeds itemMaxSize.
   * If the value is undefined
   * If incorrect cache item configuration
   * If error happened with browser storage
   * 
   * @param {String} key - the key of the item
   * @param {Object} value - the value of the item
   * @param {Object} [options] - optional, the specified meta-data
   * @return {Prmoise}
   */
  async setItem(key, value, options) {
    logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);
    const prefixedKey = this.config.keyPrefix + key;
    // invalid keys
    if (prefixedKey === this.config.keyPrefix || prefixedKey === this.cacheCurSizeKey) {
      logger.warn(`Invalid key: should not be empty or 'CurSize'`);
      return;
    }
    
    if ((typeof value) === 'undefined') {
      logger.warn(`The value of item should not be undefined!`);
      return;
    }

    const cacheItemOptions = {
      priority: options && options.priority !== undefined ? options.priority : this.config.defaultPriority,
      expires: options && options.expires !== undefined ? options.expires : (this.config.defaultTTL + getCurrTime())
    };

    if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
      logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);
      return;
    }

    const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
    
    // check wether this item is too big;
    if (item.byteSize > this.config.itemMaxSize) {
      logger.warn(`Item with key: ${key} you are trying to put into is too big!`);
      return;
    }

    try {
      // first look into the storage, if it exists, delete it.
      const val = await AsyncStorage.getItem(prefixedKey);
      if (val) {
        await this._removeItem(prefixedKey, JSON.parse(val).byteSize);
      }


      // check whether the cache is full
      if (await this._isCacheFull(item.byteSize)) {
        const validKeys = await this._findValidKeys();
        if (await this._isCacheFull(item.byteSize)) {
          const sizeToPop = await this._sizeToPop(item.byteSize);
          await this._popOutItems(validKeys, sizeToPop);
        }
      }

      // put item in the cache
      await this._setItem(prefixedKey, item);
    } catch (e) {
      logger.warn(`setItem failed! ${e}`);
    }
  }
开发者ID:lukethompson,项目名称:aws-amplify,代码行数:72,代码来源:AsyncStorageCache.ts



注:本文中的react-native.AsyncStorage类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript react-native.Dimensions类代码示例发布时间:2022-05-25
下一篇:
TypeScript react-native.AppRegistry类代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap