react native之封装离线缓存框架
请求数据=>本地有无缓存+缓存数据是否过期
=>可用
=>不可用
将代码封装成一个DataStore.js文件, 这里面主要提供:从本地获取数据,从网络获取数据,创建本地时间戳,请求数据入口
import {AsyncStorage} from 'react-native';
export default class DataStore{
// 保存数据
saveData(url,data,callback){
if(!data || !url) return;
AsyncStorage.setItem(url,JSON.stringify(this._wrapData(data)),callback);
}
_wrapData(data){
return {data:data, timestamp:new Date().getTime()};
}
//获取本地数据
fetchLocalData(url){
return new Promise((resolve,reject) => {
AsyncStorage.getItem(url,(error,result) => {
if(!error){
try{
resolve(JSON.parse(result));
}
catch(e){
reject(e);
console.error(e);
}
}
else {
reject(error);
console.error(error);
}
})
})
}
//离线缓存的入口
fetchData(url){
return new Promise((resolve,reject) => {
this.fetchLocalData(url)
.then((wrapData) => {
if(wrapData && DataStore.chekTimestampValid(wrapData.timestamp)){
resolve(wrapData);
}
else{
this.fetchNetData(url)
.then((data)=>{
resolve(this._wrapData(data));
})
.catch((error)=>{
reject(error);
})
}
})
.catch((error)=>{
this.fetchNetData(url)
.then((data)=>{
resolve(this._wrapData(data));
})
.catch((error=>{
reject(error);
}))
})
})
}
//本地缓存数据有效期检查
static chekTimestampValid(timestamp){
const currentDate = new Date();
const targetDate = new Date();
targetDate.setTime(timestamp);
if(currentDate.getMonth() !== targetDate.getMonth()) return false;
if(currentDate.getDate() !== targetDate.getDate()) return false;
if(currentDate.getHours() - targetDate.getHours() > 4) return false;
return true;
}
//获取网络数据
fetchNetData(url){
return new Promise((resolve,reject)=>{
fetch(url)
.then((response)=>{
if(response.ok){
return response.json();
}
throw new Error('Network response not ok');
})
.then((responseData)=>{
this.saveData(url,responseData)
resolve(responseData);
})
.catch((error)=>{
reject(error);
})
})
}
}
效果图主要展示:前后请求数据的时间不变,因为没有超过过期时间

此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935.
我的gitHub: (学习代码都在gitHub)
https://github.com/nwgdegitHub/

浙公网安备 33010602011771号