缓存代理
对于多次重复的操作,可以使用缓存代理的形式进行缓存(代理模式的知识,可以看我另外一篇文章设计模式-代理模式),在分页查询中,对于相同的分页,我们不希望进行重复的请求,毕竟ajax是非常消耗性能的,这个时候就可以使用缓存代理对象,当存在缓存时直接使用缓存进行获取,当不存在时才将请求交还给ajax对象。
在分页查询中的优化
在ajax中应用缓存代理,由于ajax异步的原因,所以会使用到回调或者Promise,以下是对请求的封装,使用的请求模块是axios
function getArticle(currentPage,pageSize){
return Http.mGet('/getArticle',{currentPage,pageSize}).then(e=>Promise.resolve(e.data));
}
export const proxyGetArticle = (function(){
const caches = {};
return async function(currentPage,pageSize){
const cache = Array.prototype.join.call(arguments,',');
// console.log(caches)
if(cache in caches){
return caches[cache];
}
await
getArticle(currentPage,pageSize).then(res=>{
Promise.resolve(caches[cache] = res)
})
// await
return caches[cache];
}
})()
由于事件循环的原因,调用时多次调用需要使用await
,以下是在react-hook
中的应用
useEffect(() => {
async function fetchData(){
const List = await proxyGetArticle(currentPage,pageSize)
updateBlogList(data);
}
fetchData()
}, [currentPage]);