React Native的數(shù)據(jù)持久化

前言

在數(shù)據(jù)驅(qū)動(dòng)的開發(fā)中,數(shù)據(jù)的緩存是非常重要的一環(huán)。我們從網(wǎng)絡(luò)或其他地方獲取了數(shù)據(jù),如果每次用完就拋棄勢(shì)必會(huì)浪費(fèi)CPU的性能和用戶的流量。因此,我們需要對(duì)數(shù)據(jù)進(jìn)行持久化處理。

介紹

React Native中提供了AsyncStorage類用于持久化的處理數(shù)據(jù)。
相關(guān)資料reactnative.cn

由于AsyncStorage接口比較復(fù)雜,社區(qū)中出現(xiàn)了不少基于AsyncStorage的封裝庫(kù),我們今天就使用了其中一款——react-native-storage

code

import Storage from 'react-native-storage';
import { AsyncStorage } from 'react-native';

var Cstorage = {
  init : function(){
    var storage = new Storage({
      // 最大容量,默認(rèn)值1000條數(shù)據(jù)循環(huán)存儲(chǔ)
      size: 1000,

      // 存儲(chǔ)引擎:對(duì)于RN使用AsyncStorage,對(duì)于web使用window.localStorage
      // 如果不指定則數(shù)據(jù)只會(huì)保存在內(nèi)存中,重啟后即丟失
      storageBackend: AsyncStorage,

      // 數(shù)據(jù)過期時(shí)間,默認(rèn)一整天(1000 * 3600 * 24 毫秒),設(shè)為null則永不過期
      defaultExpires: 1000 * 3600 * 24,

      // 讀寫時(shí)在內(nèi)存中緩存數(shù)據(jù)。默認(rèn)啟用。
      enableCache: true,

      // 如果storage中沒有相應(yīng)數(shù)據(jù),或數(shù)據(jù)已過期,
      // 則會(huì)調(diào)用相應(yīng)的sync方法,無縫返回最新數(shù)據(jù)。
      // sync方法的具體說明會(huì)在后文提到
      // 你可以在構(gòu)造函數(shù)這里就寫好sync的方法
      // 或是寫到另一個(gè)文件里,這里require引入
      // 或是在任何時(shí)候,直接對(duì)storage.sync進(jìn)行賦值修改
      //sync: require('./sync')  // 這個(gè)sync文件是要你自己寫的
    })

    // 對(duì)于react native
    global.storage = storage;
  },

  save:function(tkey){
    storage.save({
        key: tkey,  // 注意:請(qǐng)不要在key中使用_下劃線符號(hào)!
        data: {
          from: 'some other site',
          userid: 'some userid',
          token: 'some token'
        },
x
        // 如果不指定過期時(shí)間,則會(huì)使用defaultExpires參數(shù)
        // 如果設(shè)為null,則永不過期
        expires: null
      });
  },

  get :function(tkey){
    // 讀取
  storage.load({
    key: tkey,

    // autoSync(默認(rèn)為true)意味著在沒有找到數(shù)據(jù)或數(shù)據(jù)過期時(shí)自動(dòng)調(diào)用相應(yīng)的sync方法
    autoSync: false,

    // syncInBackground(默認(rèn)為true)意味著如果數(shù)據(jù)過期,
    // 在調(diào)用sync方法的同時(shí)先返回已經(jīng)過期的數(shù)據(jù)。
    // 設(shè)置為false的話,則始終強(qiáng)制返回sync方法提供的最新數(shù)據(jù)(當(dāng)然會(huì)需要更多等待時(shí)間)。
    syncInBackground: true,

    // 你還可以給sync方法傳遞額外的參數(shù)
    syncParams: {
    extraFetchOptions: {
    // 各種參數(shù)
    },
    someFlag: true,
    },
  }).then(ret => {
    // 如果找到數(shù)據(jù),則在then方法中返回
    // 注意:這是異步返回的結(jié)果(不了解異步請(qǐng)自行搜索學(xué)習(xí))
    // 你只能在then這個(gè)方法內(nèi)繼續(xù)處理ret數(shù)據(jù)
    // 而不能在then以外處理
    // 也沒有辦法“變成”同步返回
    // 你也可以使用“看似”同步的async/await語法

    console.error(ret.userid);
    this.setState({ user: ret });
  }).catch(err => {
    //如果沒有找到數(shù)據(jù)且沒有sync方法,
    //或者有其他異常,則在catch中返回
    console.warn(err.message);
    switch (err.name) {
        case 'NotFoundError':
            // TODO;
            break;
        case 'ExpiredError':
            // TODO
            break;
    }
  })
  }
}




export default Cstorage;


在使用時(shí),我們只需要調(diào)用相應(yīng)的方法:

Cstorage.init();
Cstorage.save('key');
Cstorage.get('key');

這個(gè)類的使用方法非常類似于Android中的SharedPreferences類。沒有深究,只是一個(gè)簡(jiǎn)單的概述,如有問題,歡迎指正。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容