react native 增長react-native-storage

現時須要使用react-native-storage本地存儲react

第一步:配置storage主文件git

mystorage.jsgithub

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

import sync from './sync';

let storage = new Storage({
    // 最大容量,默認值1000條數據循環存儲
    size: 1000,

    // 存儲引擎:對於RN使用AsyncStorage,對於web使用window.localStorage
    // 若是不指定則數據只會保存在內存中,重啓後即丟失
    storageBackend: AsyncStorage,

    // 數據過時時間,默認一成天(1000 * 3600 * 24 毫秒),設爲null則永不過時
    defaultExpires: 1000 * 3600 * 1,//一個小時

    // 讀寫時在內存中緩存數據。默認啓用。
    enableCache: true,

    // 若是storage中沒有相應數據,或數據已過時,
    // 則會調用相應的sync方法,無縫返回最新數據。
    // sync方法的具體說明會在後文提到
    // 你能夠在構造函數這裏就寫好sync的方法
    // 或是寫到另外一個文件裏,這裏require引入
    // 或是在任什麼時候候,直接對storage.sync進行賦值修改
    // sync: require('./sync')
})

storage.sync = sync;

// 全局變量
global.storage = storage;

 

第二步:配置storage的sync方法web

sync.jsjson

import { default_API_url } from '../config/index';

const sync = {
    // sync方法的名字必須和所存數據的key徹底相同
    // 方法接受的參數爲一整個object,全部參數從object中解構取出
    // 這裏能夠使用promise。或是使用普通回調函數,但須要調用resolve或reject。
    issue(params) {
        let { id, resolve, reject, syncParams: { extraFetchOptions, someFlag } } = params;

        fetch(default_API_url + '/issue/', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': extraFetchOptions.token
            },
            // body: 'id=' + id,
            ...extraFetchOptions,
        }).then(response => {
            return response.json();
        }).then(json => {
            console.log(json);
            if (json && json.results) {
                storage.save({
                    key: 'issue',
                    id,
                    data: json.results
                });

                if (someFlag) {
                    // 根據syncParams中的額外參數作對應處理
                }

                // 成功則調用resolve
                resolve && resolve(json.results);
            }
            else {
                // 失敗則調用reject
                reject && reject(new Error('data parse error'));
            }
        }).catch(err => {
            console.warn(err);
            reject && reject(err);
        });
    }
}

export default sync;

 

第三步:App.js調用storage主文件react-native

//storage
import storage from './src/util/myStorage';

 

第四步:應用中調用promise

homeComponent.js緩存

storage.load({
    key: 'issue',

    // autoSync(默認爲true)意味着在沒有找到數據或數據過時時自動調用相應的sync方法
    autoSync: true,

    // syncInBackground(默認爲true)意味着若是數據過時,
    // 在調用sync方法的同時先返回已通過期的數據。
    // 設置爲false的話,則等待sync方法提供的最新數據(固然會須要更多時間)。
    syncInBackground: true,

    // 你還能夠給sync方法傳遞額外的參數
    syncParams: {
        extraFetchOptions: {
            // 各類參數
            token: this.props.userEntity.token
        },
        someFlag: true,
    },
}).then(ret => {
    // 若是找到數據,則在then方法中返回
    // 注意:這是異步返回的結果(不瞭解異步請自行搜索學習)
    // 你只能在then這個方法內繼續處理ret數據
    // 而不能在then之外處理
    // 也沒有辦法「變成」同步返回
    // 你也能夠使用「看似」同步的async/await語法

    console.log(ret);
    this.setState({ issueData: ret });
}).catch(err => {
    //若是沒有找到數據且沒有sync方法,
    //或者有其餘異常,則在catch中返回
    console.warn(err.message);
    switch (err.name) {
        case 'NotFoundError':
            // TODO;
            break;
        case 'ExpiredError':
            // TODO
            break;
    }
})
相關文章
相關標籤/搜索