File tree Expand file tree Collapse file tree 2 files changed +29
-5
lines changed
Expand file tree Collapse file tree 2 files changed +29
-5
lines changed Original file line number Diff line number Diff line change @@ -258,8 +258,6 @@ mpx.xfetch.fetch({
258258
259259** 更加倾向于请求实时性的预先请求**
260260
261- ** 更加倾向于请求实时性的预先请求**
262-
263261在某些场景下(如耗时较长的页面跳转)我们期望能在提前发起请求作为缓存来加速进入页面的首次渲染,有需要能尽量保证数据的实时性时,可以传入 usePre .onUpdate 回调方法来获取最新的请求内容
264262
265263usePre .onUpdate 开启后,如果本次请求命中的请求缓存,依然会再次发起请求,fetch 方法返回内容变为 Promise .race ([缓存请求, 实时请求]),如果 缓存请求 先完成,则等待 实时请求 完成后,会将 实时请求 的返回内容作为 usePre .onUpdate 的参数进行回调。
@@ -282,3 +280,29 @@ mpx.xfetch.fetch({
282280
283281> tips: onUpdate 中的 response 也会经过 interceptors .response 处理,所以以上代码可能会触发两次 interceptors .response
284282
283+ ** 精细的控制缓存**
284+
285+ 默认开启 usePre 后,如果命中缓存则会将缓存清空,否则将会覆盖缓存。但有时我们希望本次usePre仅使用/ 产生缓存,此时可通过 usePre .mode 参数控制缓存的生产/ 消费模式
286+
287+ usePre .mode : 可选值 ' auto' ,' consumer' ,' producer' , 默认为' auto'
288+
289+ + auto: 存在缓存时消费缓存,不存在时生产缓存
290+ + consumer: 仅消费缓存,不存在缓存时发起网络请求,且不产生新的缓存
291+ + producer: 仅生产缓存,一定会发起网络请求,并覆盖已有缓存
292+
293+
294+ ` ` ` js
295+ mpx.xfetch.fetch({
296+ url: 'http://xxx.com',
297+ method: 'POST',
298+ data: {
299+ name: 'test'
300+ },
301+ usePre: {
302+ // 是否缓存请求
303+ enable: true,
304+ // 仅生产缓存,用于提前请求达到加速效果
305+ mode: 'producer'
306+ }
307+ })
308+ ` ` `
Original file line number Diff line number Diff line change @@ -170,7 +170,7 @@ export default class XFetch {
170170 if ( ! config . usePre . enable ) return false
171171 const cacheKey = formatCacheKey ( config . url )
172172 const cacheRequestData = this . cacheRequestData [ cacheKey ]
173- if ( cacheRequestData ) {
173+ if ( cacheRequestData && config . usePre . mode !== 'producer' ) {
174174 // 缓存是否过期:大于cacheInvalidationTime(默认为3s)则算过期
175175 const isNotExpired = Date . now ( ) - cacheRequestData . lastTime <= config . usePre . cacheInvalidationTime
176176 if ( isNotExpired && checkCacheConfig ( config , cacheRequestData ) && cacheRequestData . responsePromise ) {
@@ -242,8 +242,8 @@ export default class XFetch {
242242 promise = promise . then ( chain . shift ( ) , chain . shift ( ) )
243243 }
244244
245- // 如果开启缓存,则将 promise 存入缓存
246- if ( config . usePre . enable ) {
245+ // onlyConsumer=true是一种只消费缓存数据的模式,此模式下不会产生缓存数据
246+ if ( config . usePre . enable && config . usePre . mode !== 'consumer' ) {
247247 const cacheKey = formatCacheKey ( config . url )
248248 this . cacheRequestData [ cacheKey ] && ( this . cacheRequestData [ cacheKey ] . responsePromise = promise )
249249 }
You can’t perform that action at this time.
0 commit comments