如何将基于 Reactjs 的 PWA 更新到新版本? [英] How to update Reactjs based PWA to the new version?
问题描述
我正在开发一个基于 reactjs 的应用程序.我还对它进行了 service-worker
设置.add to home screen
之后,应用程序永远不会检查服务器是否有新的更新.
I'm developing a reactjs based application. I also made service-worker
settings on it. After add to home screen
, application never checks the server for new updates.
我也试过:
window.location.reload(true);
但它不会更新新版本.
我正在使用 Apache
服务器来为 build
文件夹提供服务,为了更新,我正在获取我的项目的新版本并在 Apache上提供服务代码>服务器.
I'm using Apache
server to serve build
folder and for update I'm getting a new build of my project and serve that on Apache
server.
推荐答案
两天后我终于解决了我的问题.问题出在 service-worker
文件中.如果页面重新加载并且服务器文件发生更改,我必须添加事件侦听器,以便更新文件.
I finally resolved my problem after two days. The problem was in service-worker
file. I had to add event listener if page reloaded and server files had changes so it will update the files.
所以我在register
函数的serviceWorker.js
中添加了这个部分:
So I added this section to serviceWorker.js
in register
function:
window.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
只是不要忘记.此侦听器在页面重新加载时调用.所以我制作 API 服务来检查是否有新版本.如果有新版本,则必须重新加载页面才能获取新文件.
Just don't forget. This listener call when page is reload. So I make API service to check there is new version or not. if there is new version , It have to reload the page to get new files.
这个问题很有帮助:如何清除 service worker 的缓存?
更新(2019 年 12 月 1 日):
我找到了更新新 PWA 的更好方法.实际上这种方式(以上)不适用于 iOS 13.所以我决定通过 API 检查更新.PWA 将当前版本发送到 API,如果有新版本发布,在 PWA 中我们应该删除所有缓存:
I found better way to update new PWA. Actually that way (above) not work on iOS 13. So I decide check update by API. PWA Send current version to API and if there is new version released , in PWA we should delete all caches:
caches.keys().then(function(names) {
for (let name of names)
caches.delete(name);
});
然后重新加载应用程序:
And after that reload application:
window.location.href = "./";
重新加载后,因为离线模式下没有缓存加载页面,所以 PWA 会检查服务器并获取新版本.
After reload because there is no cache to load pages on offline mode, so PWA will check server and get new version.
这篇关于如何将基于 Reactjs 的 PWA 更新到新版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!