如何在 React PWA 中将 API 中的数据缓存到缓存存储?

Pau*_*ula 5 reactjs service-worker progressive-web-apps

我使用 ReactJS 构建了一个渐进式 Web 应用程序,但遇到了问题。我正在使用mockApi 来获取数据。离线时,我的应用程序无法运行,因为服务工作线程仅缓存静态资产。

如何将来自mockApi 的HTTP GET 调用保存到缓存存储中?

Fra*_*sco 6

除了静态资源之外,您还可以定义要缓存的 URL:

var CACHE_NAME = 'my-cache_name';
var targetsToCache = [
  '/styles/myStyles.scss',
  'www.stackoverflow.com/'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        return cache.addAll(targetsToCache);
      })
  );
});
Run Code Online (Sandbox Code Playgroud)

然后,您必须指示您的服务工作人员拦截网络请求并查看是否与以下地址匹配targetsToCache

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response) {

         // This returns the previously cached response 
         // or fetch a new once if not already in the cache
            return response || fetch(event.request);
        })
    );
});
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣了解更多信息,我写了一系列有关渐进式 Web 应用程序的文章。