【发布时间】:2020-07-11 17:55:52
【问题描述】:
我将我的 React 应用程序转换为 PWA,它部分工作正常。
我遵循了这个教程:https://medium.com/@toricpope/transform-a-react-app-into-a-progressive-web-app-pwa-dea336bd96e6
但是这篇文章只展示了如何缓存静态数据,我还需要存储来自服务器的数据,我可以按照这篇文章的第一个答案的说明进行操作:How can I cache data from API to Cache Storage in React PWA? 并在其中插入 firebase 地址数据存储在数组urlsToCache 中,由应该存储到缓存中的文件填充。
到目前为止一切顺利,但是在将数据存储到缓存中之后,应用程序停止从服务器获取数据并仅使用缓存中的数据加载页面,即使服务器已更新。这是我需要解决的问题。
简而言之,我需要从服务器获取数据,将其存储到缓存中,以便在应用程序离线时使用它,并在每次到达服务器时更新缓存。
我正在尝试遵循本指南,但没有成功:https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#serving-suggestions
这是我的 worker.js 文件:
var CACHE_NAME = 'pwa-task-manager';
var urlsToCache = [
'/',
'/completed',
'/index.html',
'/static/js/main.chunk.js',
'/static/js/0.chunk.js',
'/static/js/1.chunk.js',
'/static/js/bundle.js',
'/calculadora',
'https://calc-marmo.firebaseio.com/clientes.json',
'https://calc-marmo.firebaseio.com/adm.json',
];
// Install a service worker
self.addEventListener('install', event => {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// Cache and return requests
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
// Update a service worker
self.addEventListener('activate', event => {
var cacheWhitelist = ['pwa-task-manager'];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
任何帮助将不胜感激。
【问题讨论】:
标签: javascript reactjs progressive-web-apps service-worker